JavaScript---查询数组符合条件的元素
for循环
最基础灵活,可通过索引控制遍历起点、终点和步长,支持
break
和continue
使用
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {console.log(arr[i]);
}
for...of 循环
直接遍历元素值(非索引),支持
break
/continue
,兼容数组、字符串、Set 等可迭代对象
使用
for (const item of arr) {if (item > 2) break; // 可提前终止console.log(item);
}
forEach()
简洁易读,但无法中断循环(除非抛异常),不返回新数组
使用
arr.forEach((item, index) => {console.log(`索引 ${index}:值 ${item}`);
});
map()方法
返回新数组(元素经回调处理),适合数据转换
使用
const doubled = arr.map(item => item * 2); // [2, 4, 6]
find()方法
返回数组中第一个满足条件的元素,找不到时返回
undefined
。
适用场景:精确查找单个对象或值。
for (const item of arr) {if (item > 2) break; // 可提前终止console.log(item);
}
简洁易读,但无法中断循环(除非抛异常),不返回新数组
使用
const users = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' }
];
// 查找 id 为 2 的用户
const user = users.find(item => item.id === 2);
console.log(user); // { id: 2, name: 'Bob' }[2,5,6](@ref)
特点
- 找到匹配项后立即停止遍历,性能高效
- 返回的是原数组的引用,修改会同步更新原数组
filter()方法
返回包含所有满足条件元素的新数组。
适用场景:需获取多个匹配项(如筛选商品列表)。
使用
const numbers = [1, 2, 3, 4, 5];
// 查找所有偶数
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4][1,4,5](@ref)
特点
- 返回新数组,不影响原数组。
- 遍历整个数组,性能低于
find()
findIndex()方法
返回首个满足条件元素的索引,找不到时返回
-1
。
适用场景:需获取元素位置(如删除或修改元素)。
使用
const fruits = ['apple', 'banana', 'cherry'];
// 查找 'banana' 的索引
const index = fruits.findIndex(fruit => fruit === 'banana');
console.log(index); // 1[3,6](@ref)
对比indexOf()
ndexOf()
仅适用于简单值(如数字、字符串),无法处理对象或复杂条件
// 仅适用于简单值
const idx = fruits.indexOf('banana'); // 1[3](@ref)
some()
方法
测试数组中是否至少有一个元素满足条件,返回布尔值。
适用场景:验证数据有效性(如检查是否有禁用用户)。
使用
const hasAdmin = users.some(user => user.role === 'admin');
console.log(hasAdmin); // true 或 false[2](@ref)
对比every()
every()
检查所有元素是否均满足条件
const allAdults = users.every(user => user.age >= 18);
对比选择
方法 | 返回值 | 是否可中断 | 适用场景 | 性能排名(从高到低) |
---|---|---|---|---|
for | - | ✅ | 精细控制索引、高性能需求 | 1(优化版最佳) |
for...of | - | ✅ | 简洁遍历值、支持异步 | 2 |
forEach | undefined | ❌ | 简单遍历、无需中断 | 3 |
map /filter | 新数组 | ❌ | 数据转换或筛选 | 4 |
find /some | 元素或布尔值 | ✅(找到即停) | 查找或条件检测 | - |
for...in | - | ✅ | 仅对象属性遍历 | 最差(避免用于数组) |