使用场景: reduce() 是一个有用的函数式编程技术,像是一般的累加,数组降维以及统计数组种出现的次数等等都可以通过该方法来实现;
接受参数:
1. Accumulator (acc) (累计器)
2. Current Value (cur) (当前值)
3. Current Index (idx) (当前索引)
4. Source Array (src) (源数组)
返回值:
- accumulator 累计器
- currentValue 当前值
- currentIndex 当前索引
- array 数组
为了方便理解,我们一般把accumulato设置为pre(前一个值),其中如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。
如何去理解initialValue呢?
我们将其看作是我们取值的一个初始值(就如英文翻译过来一样),它其实和我们当前的pre是一样的,只不过写上initialValue之后,相当于我们自己去自定义了一下当前的初始值。接下来我们直接看例子:
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// 15
第一个log信息是我们在取值的时候没有加initialValue,就是默认的第一个值(pre即索引为0的那个数字’1’开始计算的),当我们加上了initialValue且取值为5的时候(第二个log),我们当前计算的pre改为了数字’5’,这时候会导致我们的计算值5 + 1 + 2 + 3 + 4, (注意,此时的currentValue是变成了第一个值“1”了,上一个log的时候currentValue是第二个值即“2”),此时的计算值就变成了15。
用官方的原话就是这样的:
回调函数第一次执行时,accumulator
和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供
initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
比如说执行这段代码:
console.log([20, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue
}, 10))
// 输出值为40
除此之外我们如果传的initialValue不是一个具体的数字,例如传一个空数组或者一个空对象,即表示我们当前的操作是将其转换为对应的格式,以下就是利用该特点实现的一个数组的降维。
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]
我们还可以通过reduce实现数组的过滤等:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const filter_evenNumbers = numbers.filter(number => number % 2 === 0)
// [2, 4, 6, 8, 10]
const reduce_evenNumbers = numbers.reduce((acc, number) => {
if (number % 2 == 0) {
acc.push(number)
}
return acc
}, [])
// [2, 4, 6, 8, 10]