第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。
否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
reduce((previousValue, currentValue, currentIndex, array) => {}, initialValue)
// 简洁语法
reduce(callbackFn, initialValue)
// 简洁语法(无初始值)
reduce(callbackFn)
返回值:
reduce 方法的返回值就是遍历所有数组执行回调函数后的返回值。
备注:
callbackFn:回调函数
previousValue:上一次回调函数的返回值,第一次调用回调函数时,如果指定的初始值 initialValue,那么该参数值就是 initialValue,否则就是数组元素的第一个。
currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,那么当前处理的元素就是数组的第一个元素,否则的话就是第二个元素。
currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
array:用于遍历的数组。
initialValue:初始值,也就是第一次调用回调函数时参数 previousValue,是否指定初始值将会影响其它几个参数的值。
1、有初始值求和
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
const total = arr.reduce((previousValue, currentValue, currentIndex, array) => {
console.log(previousValue, currentValue, currentIndex, array)
return previousValue + currentValue; // 100 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
}, 100);
console.log(total); // 136
2、简单的数组求和
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
const total1 = arr1.reduce((previousValue, currentValue) => {
return previousValue + currentValue;
}, 0);
console.log(total1); // 36
3、数组对象求和
let arr2 = [{ x: 1 }, { x: 2 }, { x: 3 }];
const total2 = arr2.reduce((previousValue, currentValue) => {
return previousValue + currentValue.x;
}, 0);
console.log(total2); // 6
4、二维数组转一维数组
let arr3 = [[0, 1], [2, 3], [4, 5]];
const flattened = arr3.reduce((previousValue, currentValue) => {
return previousValue.concat(currentValue);
}, [])
console.log(flattened); // [0, 1, 2, 3, 4, 5]
5、计算数组元素出现次数
let names = ['小猪课堂', '张三', '李四', '王五', '小猪课堂']
let countedNames = names.reduce(function (allNames, name) {
// 判断当前数组元素是否出现过
if (name in allNames) {
allNames[name]++
} else {
allNames[name] = 1
}
return allNames
}, {})
console.log(countedNames); // {小猪课堂: 2, 张三: 1, 李四: 1, 王五: 1}