普通JS:查找索引 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
findIndex() 方法返回数组中的索引,如果元素位于
该数组满足所提供的测试功能。否则-1是
回。
[{
"Name": "Mercury",
"Temperature": "427°C",
"Position" : 1
}, {
"Name": "Venus",
"Temperature": "462°C",
"Position" : 2
}, {
"Name": "Earth",
"Temperature": "16°C",
"Position" : 3
}].findIndex(x => x.Name === "Earth")
如果您使用的是 IE 9+,则可以使用减少功能 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
reduce() 方法对累加器应用一个函数,并且每个
数组的值(从左到右)将其减少为单个
价值。
[{
"Name": "Mercury",
"Temperature": "427°C",
"Position" : 1
}, {
"Name": "Venus",
"Temperature": "462°C",
"Position" : 2
}, {
"Name": "Earth",
"Temperature": "16°C",
"Position" : 3
}].reduce(function (foundSoFar, x, i) { // Note no arrow funcion
if (foundSoFar < 0 && x.Name === "Earth") {
return i;
} else {
return foundSoFar;
}
}, -1);
或者,使用类似库的实现ramda http://ramdajs.com/docs/#findIndex