Open bibi7 opened 4 years ago
想一下一个合格的reduce都干了些什么:
先写一个只实现核心范围的polyfill:
Array.prototype.reducePolyfill = function(fn, initialValue) { //通过this获取到原数组 //判断是否具有初始值 //决定了我们的累加范围是从[initialValue, array[0]]开始或者是[array[0], array[1]] const O = this; let length = O.length, index = initialValue ? 0 : 1; let accumulator = initialValue ? initialValue : O[0] while (index < length) { // 避免出现数组empty的情况 if (O.hasOwnProperty(index)) { const item = O[index] accumulator = fn.apply(null, [accumulator, item, index, O]) } index++; } return accumulator }
test case:
[1,2,3].reducePolyfill((a,b) => { return a + b }, 10) //16 [1,2,3].reducePolyfill((a,b) => a + b) //6
继续增加一点边界条件:
Array.prototype.reducePolyfill = function(fn, initialValue) { //通过this获取到原数组 //判断是否具有初始值 //决定了我们的累加范围是从[initialValue, array[0]]开始或者是[array[0], array[1]] const O = this; let length = O.length, index = initialValue ? 0 : 1; let accumulator = initialValue ? initialValue : O[0] if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`) if (length === 0 && initialValue) throw new TypeError('can’t reduce empty Array with initialValue') while (index < length) { // 避免出现数组empty的情况 if (O.hasOwnProperty(index)) { const item = O[index] accumulator = fn.apply(null, [accumulator, item, index, O]) } index++; } return accumulator }
想一下一个合格的reduce都干了些什么:
先写一个只实现核心范围的polyfill:
test case:
继续增加一点边界条件: