js reduce()

115 阅读1分钟

reduce()是JavaScript数组的方法之一,它可以用来对数组中的元素进行累加或者累计操作。

array.reduce(callback, [initValue]) // 两个参数:回调函数 + 累加的初始值 非必填

reduce()方法接收一个回调函数作为参数,该回调函数可以设置四个参数:上一次调用回调返回的值-或者是提供的初始值initValue(accumulator),当前值(current value),当前索引(current index),以及原始数组(source array)。

const numbers = [1, 2, 3, 4, 5];
 
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 10);
 
console.log(sum); // 输出25,即10 + 1 + 2 + 3 + 4 + 5的结果
// 如果指定了初始值,那么在第一次迭代时,累加器的值将为初始值,否则将为数组中的第一个元素

在上面的例子中,我们定义了一个名为numbers的数组,然后使用reduce()方法对该数组中的元素进行累加操作。回调函数中的accumulator参数表示累加器,它初始值为空。在每次迭代中,累加器的值与当前元素的值相加,并返回新的累加器值。最终,reduce()方法返回累加器的最终值。