findIndex()方法介绍与使用

一、定义

findIndex() 方法用于查找数组中满足提供的测试函数的第一个元素的索引。如果没有找到符合条件的元素,则返回 -1

二、语法

array.findIndex(callback(element, index, array), thisArg)
  • callback: 一个函数,用于测试数组中的每个元素,接受以下参数:
    • element:当前遍历的元素。
    • index(可选):当前元素的索引。
    • array(可选):被遍历的数组。
  • thisArg(可选):执行 callbackthis 的值

三、举例

查找第一个大于 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 必须返回 truefalse
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值