作用
按顺序返回数组中的上一个元素与当前处理元素,用以处理一些复杂的逻辑
参数
- callback:
- prev 上一个元素, 如果传入初始值,则为初始值, 默认为第一个元素
- curr 当前处理元素, 如果有初始值,则为第一个元素, 默认为第二个元素
- index 下标, 如果有初始值, 则为0, 默认为1
- arr 当前处理的数组
- initValue: 初始值
使用
[1,2,3,4].reduce((prev, current, index)=>{
return current
}, 1)
//实现
Array.prototype.myReduce = (callback, initValue){
let value = initValue || this[0]
for(let i = 0 ; i < this.length ; i++){
value = callback(value, this[i+1], i, this)
}
return value
}