说明
数组的reduce()方法,接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
- reduce() 方法在每个数组元素上运行函数,以生成(减少它)单个值。
- reduce() 方法在数组中从左到右工作。另请参见 reduceRight()。
- reduce() 方法不会减少原始数组。
- reduce()函数接受了四个参数:总数(初始值/先前返回的值)
- reduce()方法可以接受一个初始值(myfunction,100)
函数声明
array.reduce(fun, initialValue)
形参:
fun:函数
initialValue:可选。传递给函数的初始值
返回值: fun每一次执行后,最后的结果
fun函数
function(total, currentValue, currentIndex, arr)
形参:
- total:必需。
- 第一次执行时:是第一个元素或
initialValue初始值 - 再次执行时,是第一次计算结束后的返回值
- 第一次执行时:是第一个元素或
- currentValue:必需。当前元素
- currentIndex:可选。当前元素的索引
- arr:可选。当前元素所属的数组对象。
返回值:必须要返回一个结果,才能继续往下算
例子
var arr = [2,4,6,8]
function fun(total,cur,index){
console.log("第"+index+"次执行,total:",total,",cur:",cur)
return total + cur // 求和
}
var res = arr.reduce( fun )
console.log("最终结果:",res)
执行结果:
第1次执行,total: 2 ,cur: 4
第2次执行,total: 6 ,cur: 6
第3次执行,total: 12 ,cur: 8
最终结果: 20
总结:
第1次执行时,
fun函数形参中,total是数组第1个元素,cur(表示当前元素) 是数组第2个元素,index(索引) 是1。
返回值:total + cur第2次执行时,
fun函数形参中,total是上一次fun函数的运行结果,cur(表示当前元素) 是数组第3个元素,index(索引) 是2。
返回值:total + cur第3次执行时,
fun函数形参中,total是上一次fun函数的运行结果,cur(表示当前元素) 是数组第4个元素,index(索引) 是3。
返回值:total + cur
传 initialValue 值
例子
var res = arr.reduce( fun , 0)
执行结果:
第0次执行,total: 666 ,cur: 2
第1次执行,total: 668 ,cur: 4
第2次执行,total: 672 ,cur: 6
第3次执行,total: 678 ,cur: 8
最终结果: 686
总结:
第1次执行时,
fun函数形参中,total是 初始值:666(与上面不同),cur(表示当前元素) 是数组 第1个元素(与上面不同),index(索引) 是0(与上面不同)。
返回值:total + cur第2次执行时,
fun函数形参中,total是上一次fun函数的运行结果,cur(表示当前元素) 是数组第2个元素,index(索引) 是2。
返回值:total + cur第3次执行时,
fun函数形参中,total是上一次fun函数的运行结果,cur(表示当前元素) 是数组第3个元素,index(索引) 是3。
返回值:total + cur第4次执行时,
fun函数形参中,total是上一次fun函数的运行结果,cur(表示当前元素) 是数组第4个元素,index(索引) 是3。
返回值:total + cur
