JavaScript 数组的 reduce 方法怎么用?用 5 个实际应用例子教会你

reduce 函数介绍

在 JavaScript 中,reduce() 是数组的一个高阶函数,作用是把数组中的元素逐个迭代处理,最终输出为一个处理结果。

reduce() 的语法如下:

array.reduce(callback, initialValue);

这个函数接受两个参数:一个回调函数和一个可选的初始值。回调函数 callback 一共可以接受四个参数:

  1. 累加器(上一次回调的返回值或初始值);
  2. 当前元素;
  3. 当前索引;
  4. 数组本身。

难点分析

需要注意的是,只有前面两个参数是必须的。这四个参数也是我当初学习 JavaScript 时最难理解的,主要是不明白被处理数组在其中循环迭代运行的原理。最后还是通过阅读其他人写的代码,然后自己照着写调试,才彻底搞懂。

5个具体的使用例子

1.计算数组元素的总和

这个例子里要重点理解初始值的作用。

const numbers = [10, 5, 7, 2]; 
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 一定要设置初始值是0,否则无法参与计算
console.log(sum); // 输出: 24

2.将数组中的字符串连接成一个句子

和上面例子差不多,迭代运算由算术改成字符串了。

const words = ["Hello", "world", "how", "are", "you"]; 
const sentence = words.reduce((accumulator, currentValue) => accumulator + " " + currentValue); 
console.log(sentence); // 输出: "Hello world how are you"

3.查找数组中的最大值

const values = [15, 8, 21, 4, 10]; 
// 这里设置初始值是负无穷,比任何数都小
const max = values.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue), -Infinity); 
console.log(max); // 输出: 21

虽然用 for 循环也能实现,但 reduce 方法明显效率更高,代码更简洁直观。

4.将二维数组扁平化为一维数组

这也是项目开发中经常用到的代码。

const nestedArray = [[1, 2], [3, 4], [5, 6]]; 
const flattenedArray = nestedArray.reduce((accumulator, currentValue) => {
accumulator.concat(currentValue), []); 
// 这里也可以用更简洁的数组展开新语法 
// [...accumulator,...currentValue]
}
console.log(flattenedArray); // 输出: [1, 2, 3, 4, 5, 6]

5.统计数组中各个元素的出现次数

const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]; 
const fruitCount = fruits.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1; 
  return accumulator; 
}, {}); 
console.log(fruitCount); // 输出: { apple: 3, banana: 2, orange: 1 }

最后返回一个对象,显示所有元素的次数,这种方法也是我工作中把数组转为对象的常用方法。

总结

上面这些例子展示了 reduce() 函数在不同场景下对数组执行的各种聚合和转换操作,总的来说,这是个非常有用的函数,希望看完这篇文章之后,能帮助你理解,像我一样逐渐喜欢使用这个方法。

原文:JavaScript 数组的 reduce 方法

猜你喜欢

转载自blog.csdn.net/weixin_45583710/article/details/134756531