reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduceRight( )
参数 | 描述 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数:
|
||||||||||
initialValue | 可选。传递给函数的初始值 |
点击按钮计算数组元素相加后的总和。
数组元素总和:
官方格式:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
简化和个人理解后的格式:array.reduce(function (total, num, index, thisArr) , initialValue)
total:函数执行完后返回的结果;
num:遍历到当前的元素;
index:当前元素的下标值;
thisArr: 使用该方法的当前数组;
initialValue: 可传递给函数的初始值;
例子目标:传入两个或两个以上的数组,返回一个以给定的原始数组排序的不包含重复值的新数组。
比如:函数传入 unite([1, 3, 2], [5, 2, 1, 4], [2, 1]) ,应返回结果 [1, 3, 2, [5], [4]];
比如:函数传入 unite([1, 3, 2], [1, [5]], [2, [4]]), 应该返回 [1, 3, 2, [5], [4]]。
方法:reduce 函数对数组中传入的元素有回调机制,可以利用其遍历元素的特点
function unite(arr1,arr2,arr3){
var l=arguments.length;
var arr=[];
for(n=0;nindex){
arr.splice(i,1) }
}
}
return arr;
}
unite([1, 3, 2], [5, 2, 1, 4], [2, 1]) //应返回 [1, 3, 2, [5], [4]]。