js的reduce方法

reduce()方法接受一个函数进行累加计算(reduce()对于空数组是不会执行回调函数的)

使用语法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

total:初始值,或者计算结束后返回的返回值(必需)

currentValue:当前元素(必需)

currentIndex:当前元素的索引

arr:当前元素所属的数组对象

假如在reduce的回调函数里面没有返回值时

var arr = [5,6,7,8,9]
arr.reduce(function(total, currentValue, currentIndex, arr){
  console.log('reduce:', total, currentValue, currentIndex, arr)
})

打印出来的结果如下

reduce: 5 6 1 [ 5, 6, 7, 8, 9 ]
reduce: undefined 7 2 [ 5, 6, 7, 8, 9 ]
reduce: undefined 8 3 [ 5, 6, 7, 8, 9 ]
reduce: undefined 9 4 [ 5, 6, 7, 8, 9 ]

由此分析:

当reduce循环时,total的初始值是数组第一位的值,由于没有return的值,所以后面都是undefined,

原文地址:https://www.cnblogs.com/wangxirui/p/11993977.html