在JavaScript开发中,数组是最常用的数据结构之一,数组查找操作几乎贯穿所有业务场景。不同的查找需求对应不同的实现方式,选择合适的方法可以提升代码的简洁性和执行效率。

基础原生查找方法
indexOf方法
indexOf是最基础的数组查找方法,用于查找指定元素在数组中首次出现的索引,找不到则返回-1,该方法严格遵循全等比较规则。
// 基本使用 const arr = [1, 2, 3, 4, 2]; const index1 = arr.indexOf(2); console.log(index1); // 输出1,第一个2的索引 const index2 = arr.indexOf(5); console.log(index2); // 输出-1,未找到元素 // 可选第二个参数,指定开始查找的位置 const index3 = arr.indexOf(2, 2); console.log(index3); // 输出4,从索引2开始查找2
includes方法
includes方法用于判断数组是否包含指定元素,返回布尔值,同样遵循全等比较,相比indexOf语义更清晰,不需要判断返回值是否为-1。
const arr = [1, 2, 3, 4]; const hasTwo = arr.includes(2); console.log(hasTwo); // 输出true const hasFive = arr.includes(5); console.log(hasFive); // 输出false // 同样支持第二个参数指定开始查找位置 const hasTwoFromIndex2 = arr.includes(2, 2); console.log(hasTwoFromIndex2); // 输出false
支持自定义条件的查找方法
find方法
find方法可以传入回调函数,查找第一个满足回调函数条件的元素,返回该元素本身,找不到则返回undefined,适合复杂条件的单个元素查找。
const users = [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 25 },
{ id: 3, name: '王五', age: 20 }
];
// 查找年龄为20的第一个用户
const targetUser = users.find(user => user.age === 20);
console.log(targetUser); // 输出 { id: 1, name: '张三', age: 20 }
// 查找不存在的元素
const notExistUser = users.find(user => user.age === 30);
console.log(notExistUser); // 输出undefined
findIndex方法
findIndex和find逻辑类似,区别在于它返回的是满足条件的元素的索引,找不到则返回-1,适合需要获取元素位置而不是元素本身的场景。
const users = [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 25 }
];
// 查找年龄为25的用户索引
const targetIndex = users.findIndex(user => user.age === 25);
console.log(targetIndex); // 输出1
// 查找不存在的元素索引
const notExistIndex = users.findIndex(user => user.age === 30);
console.log(notExistIndex); // 输出-1
查找多个匹配元素的方法
filter方法
如果需要查找所有满足条件的元素,可以使用filter方法,它返回所有满足条件的元素组成的新数组,没有匹配元素则返回空数组。
const users = [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 25 },
{ id: 3, name: '王五', age: 20 }
];
// 查找所有年龄为20的用户
const targetUsers = users.filter(user => user.age === 20);
console.log(targetUsers);
// 输出 [{ id: 1, name: '张三', age: 20 }, { id: 3, name: '王五', age: 20 }]
// 查找无匹配的情况
const emptyResult = users.filter(user => user.age === 30);
console.log(emptyResult); // 输出 []
自定义查找逻辑实现
如果不使用原生方法,也可以自己实现简单的查找逻辑,比如实现类似indexOf的功能:
function customIndexOf(arr, target, start = 0) {
for (let i = start; i < arr.length; i++) {
// 全等比较
if (arr[i] === target) {
return i;
}
}
return -1;
}
const testArr = [1, 2, 3, 2];
console.log(customIndexOf(testArr, 2)); // 输出1
console.log(customIndexOf(testArr, 2, 2)); // 输出3
console.log(customIndexOf(testArr, 5)); // 输出-1
不同查找方法的适用场景对比
| 方法名 | 返回值 | 适用场景 |
|---|---|---|
| indexOf | 索引/-1 | 简单值查找,需要获取元素位置 |
| includes | 布尔值 | 简单值查找,只需要判断是否存在 |
| find | 元素/undefined | 复杂条件查找单个元素 |
| findIndex | 索引/-1 | 复杂条件查找单个元素的位置 |
| filter | 匹配元素数组 | 查找所有满足条件的元素 |
在实际开发中,建议优先使用原生方法,它们经过引擎优化,性能和可读性都优于自定义实现。根据具体的查找需求选择对应的方法,可以让代码更简洁高效。
JavaScript数组查找indexOffindfilter修改时间:2026-06-08 22:42:21