一、定义
findIndex()
方法用于查找数组中满足提供的测试函数的第一个元素的索引。如果没有找到符合条件的元素,则返回 -1
。
二、语法
array.findIndex(callback(element, index, array), thisArg)
callback
: 一个函数,用于测试数组中的每个元素,接受以下参数:
element
:当前遍历的元素。index
(可选):当前元素的索引。array
(可选):被遍历的数组。thisArg
(可选):执行callback
时this
的值
三、举例
查找第一个大于 10 的元素索引
const numbers = [3, 7, 12, 8, 15];
const index = numbers.findIndex(num => num > 10);
console.log(index); // 输出: 2 (12 的索引)
四、 注意事项以及相近api的区别
1、findIndex()
只会返回第一个满足条件的元素的索引,即使后续还有其他符合条件的元素
2、findIndex()
只是查找索引,不会对原数组进行任何修改
3、callback
必须返回 true
或 false
callback
需要返回一个布尔值,true
代表当前元素符合条件:
4、findIndex()
在 ES6(ECMAScript 2015)中被引入,不支持 IE11 及更早版本。
4、在大数组中使用 findIndex()
时,可能会影响性能,因为它会从头开始遍历数组,直到找到第一个匹配的元素或遍历完整个数组。
5、findIndex()
vs indexOf()
const arr = [10, 20, 30];
console.log(arr.findIndex(num => num > 15)); // 输出: 1
console.log(arr.indexOf(20)); // 输出: 1
console.log(arr.indexOf(25)); // 输出: -1
6、find() vs findIndex()
-
find()
返回匹配的 元素本身,找不到返回undefined
。 -
findIndex()
返回匹配的 元素索引,找不到返回-1
。 -
需要获取元素时用
find()
,需要索引时用findIndex()
。
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" }
];
// 使用 find() 获取对象本身
const user = users.find(user => user.id === 2);
console.log(user); // 输出: { id: 2, name: "Bob" }
// 使用 findIndex() 获取对象索引
const index = users.findIndex(user => user.id === 2);
console.log(index); // 输出: 1