Array的Reduce实现原理
function myReduce (fn,baseNumber) {
// 判断是不是个数组 if (Object.prototype.toString.call(this) !== '[object Array]') { throw new TypeError('not a array') }
// 判断传入的是不是个函数 if(typeof fn !== 'function') throw new Error(`${fn} is not a function`)
// 判断数组是否为空 if(!this.length) throw new Error(`Reduce of empty array with no initial value`)
// 判断传回的基数,是否有值,没有值的话拿数组的第一个值为基数 baseNumber = (baseNumber || 0) + this[0]
let index = 0
//循环执行遍历执行fn函数 while(index < this.length) { console.log(index) baseNumber = fn(baseNumber,this[index+1] || 0, index, this) index++ } return baseNumber } Array.prototype.myReduce = myReduce a = [1,2,3,4,5,6] const x= a.myReduce(function(a,b){ return a+b },20) console.log(x)