Array.reduce()的用法

176 阅读1分钟

ES5 Array.reduce() 的用法:

Array.reduce(function(prev, cur, index, arr) {
    console.log(prevres, cur, index);
    return prevres + cur;
}, initialValue) 

reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。 描述

  • reduce 为数组中的每一个元素依次执行回调函数,
  • 回调函数第一次执行时,如果提供了 initialValue,那么第一个 previousValue 等于 initialValue ,并且currentValue 等于数组中的第一个值;
  • 如果initialValue 未被提供,那么previousValue 等于数组中的第一个值,currentValue等于数组中的第二个值