JavaScript数组常用方法find、findIndex、filter、map、flatMap及some详解
作者:浩宇软件开发
前言
这些数组方法都是ES6引入的,它们为处理数组提供了更简洁、更函数式的方式。下面我将详细介绍每个方法的用法和使用场景,并提供示例。
1. find()
作用:返回数组中满足提供的测试函数的第一个元素的值。如果没有找到则返回undefined。
使用场景:当你需要从数组中查找第一个符合条件的元素时。
const users = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 }, { id: 3, name: 'Charlie', age: 35 } ]; // 查找第一个年龄大于30的用户 const user = users.find(user => user.age > 30); console.log(user); // { id: 3, name: 'Charlie', age: 35 } // 查找不存在的用户 const notFound = users.find(user => user.age > 40); console.log(notFound); // undefined
2. findIndex()
作用:返回数组中满足提供的测试函数的第一个元素的索引。若没有找到则返回-1。
使用场景:当你需要知道某个元素在数组中的位置时。
const numbers = [10, 20, 30, 40, 50]; // 查找第一个大于25的元素的索引 const index = numbers.findIndex(num => num > 25); console.log(index); // 2 // 查找不存在的元素的索引 const notFoundIndex = numbers.findIndex(num => num > 100); console.log(notFoundIndex); // -1
3. filter()
作用:创建一个新数组,包含通过所提供函数实现的测试的所有元素。
使用场景:当你需要从数组中筛选出符合条件的多个元素时。
const products = [ { id: 1, name: 'Laptop', price: 999, inStock: true }, { id: 2, name: 'Phone', price: 699, inStock: false }, { id: 3, name: 'Tablet', price: 499, inStock: true } ]; // 筛选有库存的产品 const availableProducts = products.filter(product => product.inStock); console.log(availableProducts); // [ // { id: 1, name: 'Laptop', price: 999, inStock: true }, // { id: 3, name: 'Tablet', price: 499, inStock: true } // ] // 筛选价格低于500的产品 const cheapProducts = products.filter(product => product.price < 500); console.log(cheapProducts); // [{ id: 3, name: 'Tablet', price: 499, inStock: true }]
4. map()
作用:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后的返回值。
使用场景:当你需要对数组中的每个元素进行转换时。
const numbers = [1, 2, 3, 4]; // 将每个数字平方 const squares = numbers.map(num => num * num); console.log(squares); // [1, 4, 9, 16] // 从对象数组中提取特定属性 const names = users.map(user => user.name); console.log(names); // ['Alice', 'Bob', 'Charlie'] // 添加新属性 const usersWithStatus = users.map(user => ({ ...user, status: user.age > 30 ? 'Senior' : 'Junior' })); console.log(usersWithStatus); // [ // { id: 1, name: 'Alice', age: 25, status: 'Junior' }, // { id: 2, name: 'Bob', age: 30, status: 'Junior' }, // { id: 3, name: 'Charlie', age: 35, status: 'Senior' } // ]
5. flatMap()
作用:首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。相当于先map()再flat(1)。
使用场景:当你需要先映射然后扁平化结果时。
const sentences = ["Hello world", "Good morning", "Have a nice day"]; // 将句子拆分为单词并扁平化 const words = sentences.flatMap(sentence => sentence.split(' ')); console.log(words); // ['Hello', 'world', 'Good', 'morning', 'Have', 'a', 'nice', 'day'] // 传统方式需要先map再flat const wordsOldWay = sentences.map(sentence => sentence.split(' ')).flat(); console.log(wordsOldWay); // 同上 // 处理嵌套数组 const data = [[1], [2, 3], [4]]; const flattened = data.flatMap(arr => arr.map(x => x * 2)); console.log(flattened); // [2, 4, 6, 8]
6. some()
作用:测试数组中是否至少有一个元素通过了提供的函数的测试。返回布尔值。
使用场景:当你需要检查数组中是否有元素满足某个条件时。
const numbers = [1, 2, 3, 4, 5]; // 检查是否有偶数 const hasEven = numbers.some(num => num % 2 === 0); console.log(hasEven); // true // 检查是否有大于10的数 const hasLargeNumber = numbers.some(num => num > 10); console.log(hasLargeNumber); // false // 检查用户列表中是否有管理员 const users = [ { id: 1, name: 'Alice', isAdmin: false }, { id: 2, name: 'Bob', isAdmin: true }, { id: 3, name: 'Charlie', isAdmin: false } ]; const hasAdmin = users.some(user => user.isAdmin); console.log(hasAdmin); // true
一、查询类方法
1.includes()
检查数组是否包含某个值,返回布尔值
[1, 2, 3].includes(2); // true ['a', 'b', 'c'].includes('d'); // false
2.indexOf() / lastIndexOf()
返回元素在数组中的第一个/最后一个索引,找不到返回-1
['a', 'b', 'c', 'b'].indexOf('b'); // 1 ['a', 'b', 'c', 'b'].lastIndexOf('b'); // 3
3.every()
检查是否所有元素都满足条件
[12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true
二、操作类方法
1.concat()
合并两个或多个数组
[1, 2].concat([3, 4], [5, 6]); // [1, 2, 3, 4, 5, 6]
2.slice()
返回数组的浅拷贝部分
['a', 'b', 'c', 'd'].slice(1, 3); // ['b', 'c']
3.splice()
修改数组内容(添加/删除元素)
const arr = [1, 2, 3, 4]; arr.splice(1, 2, 'a', 'b'); // 返回 [2, 3] console.log(arr); // [1, 'a', 'b', 4]
三、转换类方法
1.join()
将数组元素连接成字符串
['Fire', 'Air', 'Water'].join(); // "Fire,Air,Water" ['Fire', 'Air', 'Water'].join('-'); // "Fire-Air-Water"
2. reduce() / reduceRight()
对数组元素执行累加器函数
[1, 2, 3, 4].reduce((acc, val) => acc + val); // 10 [1, 2, 3, 4].reduce((acc, val) => acc + val, 5); // 15 (带初始值)
四、排序类方法
1.sort()
对数组元素进行排序(原地修改)
const fruits = ['banana', 'apple', 'pear']; fruits.sort(); // ['apple', 'banana', 'pear'] const numbers = [4, 2, 5, 1, 3]; numbers.sort((a, b) => a - b); // [1, 2, 3, 4, 5]
2. reverse()
反转数组顺序(原地修改)
['a', 'b', 'c'].reverse(); // ['c', 'b', 'a']
五、迭代类方法
1. forEach()
对每个数组元素执行函数
['a', 'b', 'c'].forEach((item, index) => { console.log(`${index}: ${item}`); }); // 0: a // 1: b // 2: c
六、新增元素方法
1.push() / pop()
在数组末尾添加/删除元素
const arr = [1, 2]; arr.push(3); // 返回新长度3,arr变为[1, 2, 3] arr.pop(); // 返回3,arr变回[1, 2]
2.unshift() / shift()
在数组开头添加/删除元素
const arr = [1, 2]; arr.unshift(0); // 返回新长度3,arr变为[0, 1, 2] arr.shift(); // 返回0,arr变回[1, 2]
七、ES6+新增方法
1. flat()
将嵌套数组扁平化
[1, 2, [3, 4]].flat(); // [1, 2, 3, 4] [1, 2, [3, [4, 5]]].flat(2); // [1, 2, 3, 4, 5]
2. fill()
用固定值填充数组
[1, 2, 3].fill(0); // [0, 0, 0] [1, 2, 3, 4].fill(5, 1, 3); // [1, 5, 5, 4]
3. Array.from()
从类数组对象创建新数组
Array.from('foo'); // ['f', 'o', 'o'] Array.from([1, 2, 3], x => x + x); // [2, 4, 6]
总结对比
方法 | 返回值 | 是否修改原数组 | 使用场景 |
---|---|---|---|
concat() | 新数组 | 否 | 合并数组 |
every() | 布尔值 | 否 | 检查所有元素是否满足条件 |
fill() | 修改后的数组 | 是 | 填充数组元素 |
filter() | 新数组 | 否 | 筛选元素 |
find() | 第一个匹配元素或undefined | 否 | 查找单个元素 |
findIndex() | 索引或-1 | 否 | 查找元素位置 |
flat() | 新数组 | 否 | 扁平化嵌套数组 |
flatMap() | 新数组 | 否 | 映射后扁平化 |
forEach() | undefined | 否 | 遍历数组 |
includes() | 布尔值 | 否 | 检查是否包含值 |
indexOf() | 索引或-1 | 否 | 查找元素首次出现位置 |
join() | 字符串 | 否 | 连接数组为字符串 |
map() | 新数组 | 否 | 转换每个元素 |
pop() | 删除的元素 | 是 | 移除最后一个元素 |
push() | 新长度 | 是 | 末尾添加元素 |
reduce() | 累加结果 | 否 | 累加计算 |
reverse() | 反转后的数组 | 是 | 反转数组顺序 |
shift() | 删除的元素 | 是 | 移除第一个元素 |
slice() | 新数组 | 否 | 截取数组部分 |
some() | 布尔值 | 否 | 检查是否有元素满足条件 |
sort() | 排序后的数组 | 是 | 数组排序 |
splice() | 删除的元素数组 | 是 | 添加/删除元素 |
unshift() | 新长度 | 是 | 开头添加元素 |
这些方法都遵循函数式编程的原则,不会修改原数组,而是返回新数组或值。它们可以链式调用,使得代码更加简洁和可读。
到此这篇关于JavaScript数组常用方法find、findIndex、filter、map、flatMap及some的文章就介绍到这了,更多相关JS数组常用方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!