Array.prototype.myReduce = function(fn,initValue){ if(this.length == 0){ throw new Error('Reduce of empty array with no initial value') } let i,total; if(initValue){ total = initValue i = 0; }else{ total = this[0] i = 1; } for(;i < this.length;i++){ let item = this[i] total = fn(total,item,i,this) } return total }
有初始值,下表从0开始;无初始值,下标从1开始。