javascript的数组之reduce()

时间:2023-03-08 20:51:44
javascript的数组之reduce()

reduce()方法对累加器和数组中的每个元素(从左到右)应用到一个函数中,最终得到一个值并返回

 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));
// expected output: 15

参数:

第一个:callback回调函数(accumulator, currentValue, currentIndex, array)

第二个:initalValue初始值,作为第一个执行回调函数的accumulator值,reduce的index初始索引为0。如果没有initalValue,则使用数组第一个元素作为accumulator值,并且从第二个元素开始执行回调函数,此时reduce初始索引为1。

返回值:函数累计的数组元素叠加值。