reduce()
是一个数组方法,用于将数组中的所有元素归纳为单个值。它接收两个参数:一个回调函数和一个初始值。
回调函数包含四个参数:累加器、当前元素、当前索引和原始数组。该回调函数在数组的每个元素上调用一次,执行归纳操作,最后返回一个归纳后的值。
基本语法:
array.reduce(callback[, initialValue]);
其中,array
是要操作的数组,callback
是回调函数,initialValue
是可选的初始值。
reduce()
方法通常用于以下几个方面:
1.将数组中的元素累加为一个值
你可以使用 reduce()
方法将数组中的所有元素累加为一个总和或者是一个平均值。例如,以下代码将计算具有两个数值的数组 [1, 2]
的总和
const sum = [1, 2].reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // 3
在第一次调用回调函数时,accumulator
参数将设置为 0
,current
参数将设置为数组中的第一个元素 1
,然后回调函数返回了 0 + 1
这个结果作为下一次 accumulator
参数的值。第二次调用回调函数时将计算 1 + 2
并返回最后的结果 3
。
2.将数组转换为另一个数组或对象
使用 reduce()
方法,你可以将一个数组转换为另一个数组或对象。例如,以下代码将数组 [1, 2, 3]
中的每个元素平方,并返回一个新的数组:
const squaredArray = [1, 2, 3].reduce((accumulator, current) => {
const squared = current * current;
accumulator.push(squared);
return accumulator;
}, []);
console.log(squaredArray); // [1, 4, 9]
在第一次调用回调函数时,accumulator
参数将设置为一个空数组 []
,current
参数将设置为数组中的第一个元素 1
,然后回调函数计算并返回了 1
的平方值 1
,将其加入到 accumulator
数组中并返回。第二次调用回调函数时将计算 2
的平方值 4
并加入到 accumulator
中,以此类推。
3.过滤、去重或分组某些元素
使用 reduce()
方法,你可以对数组元素进行过滤、去重或分组。例如,以下代码将数组 [1, 2, 3, 4, 5, 6, 7, 8, 9]
中的偶数元素筛选出来,并返回一个新的数组:
const evenArray = [1, 2, 3, 4, 5, 6, 7, 8, 9].reduce((accumulator, current) => {
if (current % 2 === 0) {
accumulator.push(current);
}
return accumulator;
}, []);
console.log(evenArray); // [2, 4, 6, 8]