findindex 是 javascript 数组方法,返回首个满足条件元素的索引,未找到返回 -1;不修改原数组,支持回调函数自定义条件,适用于数字、对象、字符串等多场景查找。

findIndex 是 JavaScript 数组的内置方法,用于查找第一个满足条件的元素的索引。它不会修改原数组,返回的是匹配项的下标(从 0 开始),没找到则返回 -1。
基本用法:传入一个判断函数
你需要提供一个回调函数,对每个元素执行判断,一旦返回 true,就立即返回当前索引,不再继续遍历。
语法:array.findIndex(callback(element, index, array), thisArg)
- element:当前遍历的元素
- index(可选):当前元素的索引
- array(可选):调用 findIndex 的原数组
- thisArg(可选):指定回调函数中 this 的值
常见使用场景示例
查找数字数组中第一个大于 10 的数的索引:
const nums = [3, 7, 12, 5, 15]; const idx = nums.findIndex(n => n > 10); // 返回 2(因为 nums[2] === 12)
查找对象数组中某个 id 对应的对象索引:
const users = [
{ id: 101, name: 'Alice' },
{ id: 203, name: 'Bob' },
{ id: 156, name: 'Charlie' }
];
const targetIdx = users.findIndex(user => user.id === 203); // 返回 1
配合严格相等或 includes 判断字符串/数组:
const fruits = ['apple', 'banana', 'cherry'];
const bananaIdx = fruits.findIndex(fruit => fruit === 'banana'); // 1
const hasBerry = fruits.findIndex(fruit => fruit.includes('berry')) !== -1; // true
注意边界情况
- 空数组调用 findIndex 会直接返回 -1
- 回调函数必须明确返回布尔值;返回 falsy 值(如 0、''、null)会被当作 false,不中断查找
- 只找第一个匹配项,后续即使还有符合条件的元素也不会被处理
- 如果想获取所有匹配索引,不能用 findIndex,应考虑 map + filter 或 reduce
和 indexOf、find 的区别
- indexOf 只支持全等(===)查找简单值,不支持复杂条件
- find 返回匹配的元素本身,而 findIndex 返回它的索引
- 三者都只返回第一个匹配结果,且不改变原数组
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











