indexOf 和 findIndex 都是 JavaScript 数组的查找方法,但它们的查找逻辑和适用场景有显著区别。以下是详细对比:
-
核心区别
特性 indexOf findIndex
查找依据 严格相等(===) 回调函数(自定义条件)
返回值 第一个匹配元素的索引(未找到返回 -1) 第一个满足回调的元素的索引(未找到返回 -1)
适用场景 精确值查找(如数字、字符串) 复杂条件查找(如对象属性、逻辑判断)
性能 更高(直接遍历比较) 稍低(需执行回调函数) -
使用示例
(1) indexOf:严格匹配值const arr = [10, 20, 30, 20]; // 查找值为 20 的第一个索引 console.log(arr.indexOf(20)); // 1(直接匹配值) // 未找到返回 -1 console.log(arr.indexOf(99)); // -1
(2) findIndex:自定义条件
const users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" } ]; // 查找 name 为 "Bob" 的对象的索引 console.log(users.findIndex(user => user.name === "Bob")); // 1 // 查找 id > 2 的第一个对象的索引 console.log(users.findIndex(user => user.id > 2)); // 2
-
关键差异场景
(1) 查找对象const obj = { id: 2 }; const arr = [{ id: 1 }, obj, { id: 3 }]; // indexOf 无法查找对象(除非引用相同) console.log(arr.indexOf({ id: 2 })); // -1(新对象,引用不同) console.log(arr.indexOf(obj)); // 1(同一引用) // findIndex 可通过属性查找 console.log(arr.findIndex(item => item.id === 2)); // 1
(2) 查找 NaN
const arr = [1, NaN, 3]; // indexOf 无法识别 NaN console.log(arr.indexOf(NaN)); // -1(因为 NaN !== NaN) // findIndex 可以识别 console.log(arr.findIndex(x => isNaN(x))); // 1
(3) 复杂条件
const numbers = [10, 20, 30, 40]; // 查找第一个大于 25 的数的索引 console.log(numbers.findIndex(x => x > 25)); // 2 // indexOf 无法直接实现!
-
如何选择?
-
用 indexOf 当:
-
查找基本类型值(数字、字符串、布尔值等)。
-
需要高性能的简单查找。
-
-
用 findIndex 当:
-
查找对象或需要自定义条件(如属性匹配、逻辑判断)。
-
需要处理特殊值(如 NaN)。
-
-
-
总结
需求 | 推荐方法 | 原因 |
---|---|---|
精确值匹配(基本类型) | indexOf | 简洁高效 |
对象或复杂条件匹配 | findIndex | 支持回调,灵活强大 |
查找 NaN | findIndex | indexOf 无法识别 NaN |
一句话总结:
indexOf
是“严格相等查找”,findIndex
是“智能回调查找”。