定义和用法
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数(重点理解回调的两个参数)
第一个参数(callback):function(total, currentValue, currentIndex, arr)
- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
- currentValue (数组中当前被处理的元素)
- index (当前元素在数组中的索引)
- array (调用 reduce 的数组)
第二个参数:initialValue (作为第一次调用 callback 的第一个参数。) ,该值也决定了返回值类型
- 如果不给这个值,那么默认从第二项开始遍历,如