在JavaScript中,reduce
方法用于对数组中的每个元素执行一个reducer函数(累积器),将其结果汇总为单个返回值。这是处理数组以生成总结值或进行复杂操作的一种强大方式。
基本语法
1array.reduce(callbackFn[, initialValue]);
-
callbackFn: 执行数组中每个值的函数,包含四个参数:
accumulator
: 累积器,累计回调函数的返回值。它是上一次调用回调时返回的值,或者是初始值(initialValue)。currentValue
: 数组中当前正在处理的元素。currentIndex
(可选): 当前元素在数组中的索引。默认从0开始。array
(可选): 调用了reduce
方法的数组本身。
-
initialValue(可选): 传递给函数的初始值。如果未提供,则
accumulator
的初始值为数组的第一个元素,且currentValue
将从数组的第二个元素开始。
示例
求和
1let numbers = [1, 2, 3, 4, 5];
2let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
3console.log(sum); // 输出: 15
计算数组中所有数字的乘积
1let product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
2console.log(product); // 输出: 120
将数组扁平化
1let arrays = [[0, 1], [2, 3], [4, 5]];
2let flatArray = arrays.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
3console.log(flatArray); // 输出: [0, 1, 2, 3, 4, 5]
查找最大值
1let max = numbers.reduce((maxSoFar, currentValue) => currentValue > maxSoFar ? currentValue : maxSoFar, numbers[0]);
2console.log(max); // 输出: 5
通过这些示例可以看出,reduce
方法非常灵活,可以用于多种数组处理场景,从简单的求和到复杂的转换和计算。