// callback:函数中包含四个参数
// - previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
// - currentValue (数组中当前被处理的元素)
// - index (当前元素在数组中的索引)
// - array (调用的数组)
// initialValue (作为第一次调用 callback 的第一个参数。)
// const arr = [1, 2, 3, 4, 5]
// const sum = arr.reduce((pre, item) => {
// return pre + item
// }, 0)
// console.log(sum) // 15
Array.prototype.myReduce = function (fn, initialValue){
let arr = this.slice()
let per, startIndex
per = initialValue? initialValue: arr[0]
startIndex = initialValue? 0: 1
for(let i=startIndex; i<arr.length; i++){
per = fn.call(null,per,arr[i],i,this)
}
return per
}
console.log([1,2,3,4,5].myReduce((pre, item)=>{
return pre + item
}, 0))
console