Array.prototype.reduce
注意考虑没有传入初始值的情况
// 测试数据arr
let arr = [ 1, 2, 3, 4]
Array.prototype.myReduce = function (fn, initValue ) {
let result
if (initValue) {
result = fn(initValue, this[0], 0, this)
for (let i = 1; i < this.length; i++) {
result = fn(result, this[i], i, this)
}
} else {
result = fn(this[0], this[1], 1, this)
for (let i = 2; i < this.length; i++) {
result = fn(result, this[i], i, this)
}
}
// console.log(result);
return result
}
// 调用示例
arr.myReduce((accumulator, currentValue, i, array) => {
console.log(accumulator, currentValue, i, array + '-------');
return accumulator + currentValue
},1)