JavaScript中的数组方法:map、filter和reduce详解

原创
admin 6个月前 (06-16) 阅读数 29 #JavaScript

JavaScript数组提供了许多强大的内置方法,其中map、filter和reduce是最常用且功能强大的几个方法。它们可以帮助我们以声明式的方式处理数组数据,而不需要使用传统的for循环。

1. Array.prototype.map()

map()方法创建一个新数组,其结果是该数组中的每个元素调用一次提供的函数后的返回值。

基本语法

const newArray = arr.map(function callback(currentValue[, index[, array]]) {    // 返回新数组的元素}[, thisArg])

示例

const numbers = [1, 2, 3, 4];const doubled = numbers.map(num => num * 2);console.log(doubled); // [2, 4, 6, 8]// 处理对象数组const users = [    { name: 'Alice', age: 25 },    { name: 'Bob', age: 30 },    { name: 'Charlie', age: 35 }];const names = users.map(user => user.name);console.log(names); // ['Alice', 'Bob', 'Charlie']

2. Array.prototype.filter()

filter()方法创建一个新数组,其中包含通过所提供函数测试的所有元素。

基本语法

const newArray = arr.filter(function callback(element[, index[, array]]) {    // 返回true保留该元素,false则不保留}[, thisArg])

示例

const numbers = [1, 2, 3, 4, 5, 6];const evens = numbers.filter(num => num % 2 === 0);console.log(evens); // [2, 4, 6]// 过滤对象数组const products = [    { name: 'Laptop', price: 1000 },    { name: 'Phone', price: 500 },    { name: 'Tablet', price: 300 }];const affordable = products.filter(product => product.price < 600);console.log(affordable); // [{ name: 'Phone', price: 500 }, { name: 'Tablet', price: 300 }]

3. Array.prototype.reduce()

reduce()方法对数组中的每个元素执行一个由您提供的reducer函数,将其结果汇总为单个返回值。

基本语法

const result = arr.reduce(function callback(accumulator, currentValue[, index[, array]]) {    // 返回累积值}[, initialValue])

示例

const numbers = [1, 2, 3, 4];const sum = numbers.reduce((acc, curr) => acc + curr, 0);console.log(sum); // 10// 统计数组中每个元素出现的次数const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'apple'];const count = fruits.reduce((acc, fruit) => {    acc[fruit] = (acc[fruit] || 0) + 1;    return acc;}, {});console.log(count); // { apple: 3, banana: 1, orange: 2 }

综合使用示例

const orders = [    { id: 1, product: 'Laptop', price: 1200, quantity: 1 },    { id: 2, product: 'Mouse', price: 50, quantity: 2 },    { id: 3, product: 'Keyboard', price: 80, quantity: 1 },    { id: 4, product: 'Monitor', price: 300, quantity: 1 },    { id: 5, product: 'Headphones', price: 100, quantity: 3 }];// 计算总销售额(价格*数量的总和)const totalSales = orders    .map(order => order.price * order.quantity) // 先计算每个订单的总价    .reduce((sum, orderTotal) => sum + orderTotal, 0); // 再求和console.log(totalSales); // 1200 + 100 + 80 + 300 + 300 = 1980// 找出购买数量大于1的产品名称const bulkProducts = orders    .filter(order => order.quantity > 1)    .map(order => order.product);console.log(bulkProducts); // ['Mouse', 'Headphones']

总结

map():转换数组中的每个元素,生成一个长度相同的新数组filter():筛选数组中的元素,生成一个可能长度不同的新数组reduce():将数组元素累积为单个值,功能最为强大

这些方法可以单独使用,也可以链式调用,帮助我们以更加函数式和声明式的方式处理数组数据,使代码更加简洁易读。

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。

作者文章
热门
最新文章
标签列表