reduce 方法对累计器和数组中的每个元素(从左到右)应用一个函数,将其简化为单个值。
reducer 函数接收4个参数:
- Accumulator (acc) (累计器)
- Current Value (cur) (当前值)
- Current Index (idx) (当前索引)
- Source Array (src) (源数组)
有默认参数
const arr = [1, 2, 3]
let result = arr.reduce(function(val, item, index, origin) {
return val + item
}, 0)
无默认参数
result = arr.reduce(function(val, item, index, origin) {
return val + item
})
求平均值
result = arr.reduce(function(val, item, index, origin) {
const res = val + item
if (index === origin.length-1) {
return res/origin.length
} else {
return res
}
})
console.log(result)
实现reduce
Array.prototype.myRedece = function(reducer, initValue){
for (let i = 0; i < this.length; i++) {
initValue = reducer(initValue, this[i], i, this)
}
return initValue
}
const res = arr.myRedece(function(val, item){
return val + item
}, 0)
console.log(res)
实现reduceRight
Array.prototype.myRedeceRight = function(reducer, initValue){
for (let i = this.length -1 ; i >= 0; i--) {
initValue = reducer(initValue, this[i], i, this)
}
return initValue
}
const res1 = arr.myRedece(function(val, item){
return val + item
}, 0)
console.log(res1)