下面给你整理一份 JavaScript 数组常用方法详解,包括 find、findIndex、filter、map、flatMap 和 some,每个方法配合 原理说明 + 使用示例 + 注意事项,适合新手和进阶复习。
🔥 1️⃣ find 方法
作用:
返回 数组中第一个符合条件的元素,如果没有符合条件的返回 undefined。
语法:
arr.find(callback(element, index, array))
示例:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: 'Bob' }
注意事项:
- 只返回第一个符合条件的元素
- 回调函数返回
true时停止遍历
🔥 2️⃣ findIndex 方法
作用:
返回 数组中第一个符合条件的元素索引,找不到返回 -1。
语法:
arr.findIndex(callback(element, index, array))
示例:
const index = users.findIndex(u => u.name === 'Charlie');
console.log(index); // 2
注意事项:
- 与
find类似,但返回索引 - 用于删除或更新特定元素
🔥 3️⃣ filter 方法
作用:
返回 所有符合条件的元素组成的新数组。
语法:
arr.filter(callback(element, index, array))
示例:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(n => n % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
注意事项:
- 不改变原数组
- 回调返回
true的元素才会被保留 - 返回数组长度可为 0
🔥 4️⃣ map 方法
作用:
对数组每个元素执行回调,并返回 新数组,长度与原数组相同。
语法:
arr.map(callback(element, index, array))
示例:
const nums = [1, 2, 3];
const squares = nums.map(n => n * n);
console.log(squares); // [1, 4, 9]
注意事项:
- 不改变原数组
- 常用于数据格式转换
- 回调返回值组成新数组
🔥 5️⃣ flatMap 方法
作用:
先执行 map,然后 扁平化一层。常用于处理嵌套数组。
语法:
arr.flatMap(callback(element, index, array))
示例 1:扁平化一层数组
const arr = [1, 2, 3];
const result = arr.flatMap(n => [n, n * 2]);
console.log(result); // [1,2,2,4,3,6]
示例 2:处理嵌套数组
const nested = [[1,2], [3,4]];
const flattened = nested.flatMap(x => x.map(n => n*2));
console.log(flattened); // [2,4,6,8]
注意事项:
- 只扁平化一层
- 等同于
arr.map(...).flat(1) - 原数组不变
🔥 6️⃣ some 方法
作用:
检测数组中 是否至少有一个元素符合条件,返回布尔值。
语法:
arr.some(callback(element, index, array))
示例:
const numbers = [1, 2, 3, 4];
const hasEven = numbers.some(n => n % 2 === 0);
console.log(hasEven); // true
注意事项:
- 回调返回
true时立即返回true,短路 - 常用于判断条件是否存在
🔥 7️⃣ 对比总结
| 方法 | 返回值 | 停止条件 | 原数组改变 |
|---|---|---|---|
| find | 第一个符合条件的元素 | 找到第一个 | 否 |
| findIndex | 第一个符合条件的索引 | 找到第一个 | 否 |
| filter | 符合条件的所有元素数组 | 遍历完全部 | 否 |
| map | 新数组,每个元素经过回调 | 遍历完全部 | 否 |
| flatMap | 新数组(map + 扁平化一层) | 遍历完全部 | 否 |
| some | 布尔值 | 找到第一个符合 | 否 |
🔥 8️⃣ 小结
- 查找单个元素 →
find/findIndex - 过滤多个元素 →
filter - 转换数组 →
map/flatMap - 判断存在性 →
some
Tip:结合
filter+map/flatMap可以实现复杂数组操作
发表回复