JavaScript中的数组方法:map、filter和reduce
原创数组是JavaScript中最常用的数据结构之一,ES5提供了许多实用的数组方法,其中map、filter和reduce尤为强大。这些方法可以帮助我们以更声明式的方式处理数组数据,避免使用传统的for循环。
map方法
map()方法创建一个新数组,其结果是该数组中的每个元素调用一次提供的函数后的返回值。
const numbers = [1, 2, 3, 4, 5];// 将每个数字乘以2const doubled = numbers.map(num => num * 2);console.log(doubled); // [2, 4, 6, 8, 10]// 将数字转换为字符串const stringNumbers = numbers.map(num => num.toString());console.log(stringNumbers); // ['1', '2', '3', '4', '5']filter方法
filter()方法创建一个新数组,其中包含通过所提供函数测试的所有元素。
const numbers = [1, 2, 3, 4, 5];// 过滤出偶数const evens = numbers.filter(num => num % 2 === 0);console.log(evens); // [2, 4]// 过滤出大于3的数字const greaterThanThree = numbers.filter(num => num > 3);console.log(greaterThanThree); // [4, 5]reduce方法
reduce()方法对数组中的每个元素执行一个由您提供的reducer函数,将其结果汇总为单个返回值。
const numbers = [1, 2, 3, 4, 5];// 计算总和const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);console.log(sum); // 15// 找出最大值const max = numbers.reduce((a, b) => Math.max(a, b));console.log(max); // 5组合使用
这些方法可以组合使用,创建更复杂的数据转换管道。
const products = [ { name: 'iPhone', price: 999, inStock: true }, { name: 'Samsung', price: 799, inStock: false }, { name: 'Google Pixel', price: 699, inStock: true }, { name: 'OnePlus', price: 549, inStock: true }];// 获取所有有货产品的名称和价格,并计算总价const result = products .filter(product => product.inStock) .map(product => ({ name: product.name, price: product.price })) .reduce((total, product) => total + product.price, 0);console.log(result); // 2247 (999 + 699 + 549)总结
map():转换数组中的每个元素,生成一个长度相同的新数组filter():筛选数组中符合条件的元素,生成一个新数组reduce():将数组元素聚合成单个值这些方法使代码更加简洁、易读,并且避免了直接修改原始数组,符合函数式编程的不变性原则。它们在处理数据集合时特别有用,是现代JavaScript开发中不可或缺的工具。
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。
开发学习网



