Array.prototype.reduce = function(fn,init){
//this指向调用reduce的数组
//console.log(this);//
const hasInit = arguments.length>1;
let result = hasInit?init:this[0];
const startIndex = hasInit?0:1;
for(let i = startIndex;i<this.length;i++){
result = fn(result,this[i]);
}
return result;
}
const arr = [1,2,3];
const res = Array.prototype.reduce.call(arr,(a)=>a*2,10);
console.log(res);//80
手写Array的reduce
于 2024-03-14 21:24:42 首次发布