1、定义和用法
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 递归。
注意: reduce() 对于空数组是不会执行回调函数的。
2、实例:
-
计算数组的和
let a = [1, 1, 2, 3, 1, 4, 4, 5, 6, 8]
let sum = (arr) =>{
let arrSum = arr.reduce((all, next) =>{
return all + next
})
return arrSum
}
console.log(sum(a)) //35
-
计算数组的最大值
let a = [1, 1, 2, 3, 1, 4, 4, 5, 6, 8]
let max = (arr) =>{
let max=arr.reduce((max,next)=>{
return Math.max(max,next)
})
return max
}
console.log(max(a)) //8
-
数组去重
//数组去重
let a = [1, 1, 2, 3, 1, 4, 4, 5, 6, 8]
let unique = (arr) =>{
let arrTemp=[]
let uni = arr.reduce((pre, next) =>{
arrTemp.indexOf(next)===-1&&arrTemp.push(next); //三元表达式简写
return arrTemp
})
return uni
}
console.log(unique(a)) //[1, 2, 3, 4, 5, 6, 8]
/*或者使用reduce的第三个参数*/
let a = [1, 1, 2, 3, 1, 4, 4, 5, 6, 8]
let unique = (arr) =>{
let uni = arr.reduce((pre, next) =>{
pre.indexOf(next)===-1&&pre.push(next);
return pre
},[]) //初始值的pre= [] 是一个空数组,就有了indexOf 方法。 return uni
}
console.log(unique(a)) //[1, 2, 3, 4, 5, 6, 8]
3、reduceRight的用法
该方法用法与reduce()其实是相同的,只是遍历的顺序相反,它是从数组的最后一项开始,向前遍历到第一项。