Array.prototype.reduce2 = function(fn, initialValue){
var O = Object(this)
var len = this.length;
var acc = initialValue || O[0];
var i = initialValue ? 0 : 1;
for(;i<len;i++){
acc = fn(acc, O[i], i, O)
}
return acc;
}
let nums = [1, 2, 3];
let obj = {val: 5};
let result = nums.reduce2(function(acc, cur, index,array) {
return acc + cur;
}, 1);
console.log(result);
reduce
参数
callback 执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数
return acc; } let nums = [1, 2, 3]; let obj = {val: 5}; let result = nums.reduce2(function(acc, cur, index,array) { return acc + cur; }, 1); console.log(result);