ES6 添加了一个名为 array.findIndex() 的新方法,它允许您查找数组中满足提供的测试函数的第一个元素。
该方法返回满足测试函数的元素的索引,如果没有元素通过测试,则返回 -1。
下面说明了该方法的语法:
语法
findIndex(testFn(element[, index[, array]])[, thisArg])
参数
- testFn - 要对数组中的每个元素执行,直到函数返回 ,指示已找到该元素。
- element - 是数组中的当前元素。
- index - 是正在处理的当前元素的索引。
- array - 是调用 的数组。
- thisArg - 它会对数组中的每个元素执行 ,直到找到返回 true 值的那个元素,一旦找到这样的元素,它就会立即返回该元素的索引。
示例1
返回数组中第一次出现的数字 7 的索引:
let ranks = [1, 5, 7, 8, 10, 7];
let index = ranks.findIndex(rank => rank === 7);
console.log(index);
输出
2
示例2
使用该方法获取数组中索引 2 之后第一次出现的数字 7 的索引:
let ranks = [1, 5, 7, 8, 10, 7];
let index = ranks.findIndex(
(rank, index) => rank === 7 && index > 2
);
console.log(index);
输出
5
示例3
以下示例使用 Array 方法查找价格大于 1000 的第一个产品的索引:
const products = [
{ name: 'Phone', price: 999 },
{ name: 'Computer', price: 1999 },
{ name: 'Tablet', price: 995 },
];
const index = products.findIndex(product => product.price > 1000);
console.log(index); // 1