JavaScript 自己動(dòng)手?jǐn)]源碼之 reduce

//判斷初始值是存在 ?//reduce ?Array.prototype.myReduce = function(fn, firstVal) { ???let val = firstVal || this[0] ???let startIndex = firstVal ? 0 : 1 ???for(let i = startIndex; i < this.length; i++) { ?????val = fn(val, this[i], i, this) ??} ???return val ?} ? ?//reduceRight ?Array.prototype.myReduce = function(fn, firstVal) { ???let val = firstVal || this[this.length - 1] ???let startIndex = firstVal ? (this.length - 1) : (this.length - 2) ???for(let i = startIndex; i < this.length; i++) { ?????val = fn(val, this[i], i, this) ??} ???return val ?}
標(biāo)簽: