菜鸟-创作你的创作

JavaScript数组常用方法find、findIndex、filter、map、flatMap及some详解

下面给你整理一份 JavaScript 数组常用方法详解,包括 findfindIndexfiltermapflatMapsome,每个方法配合 原理说明 + 使用示例 + 注意事项,适合新手和进阶复习。


🔥 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' }

注意事项:


🔥 2️⃣ findIndex 方法

作用:
返回 数组中第一个符合条件的元素索引,找不到返回 -1

语法:

arr.findIndex(callback(element, index, array))

示例:

const index = users.findIndex(u => u.name === 'Charlie');
console.log(index); // 2

注意事项:


🔥 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]

注意事项:


🔥 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]

注意事项:


🔥 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

注意事项:


🔥 7️⃣ 对比总结

方法返回值停止条件原数组改变
find第一个符合条件的元素找到第一个
findIndex第一个符合条件的索引找到第一个
filter符合条件的所有元素数组遍历完全部
map新数组,每个元素经过回调遍历完全部
flatMap新数组(map + 扁平化一层)遍历完全部
some布尔值找到第一个符合

🔥 8️⃣ 小结

  1. 查找单个元素find / findIndex
  2. 过滤多个元素filter
  3. 转换数组map / flatMap
  4. 判断存在性some

Tip:结合 filter + map / flatMap 可以实现复杂数组操作

退出移动版