问答题1196/1593实现 Array.prototype.reduce()

难度:
2021-07-06 创建

参考答案:

1Array.prototype.reduce = function(callback, initialValue) { 2 if (this == undefined) { 3 throw new TypeError('this is null or not defined'); 4 } 5 if (typeof callback !== 'function') { 6 throw new TypeError(callbackfn + ' is not a function'); 7 } 8 const O = Object(this); 9 const len = this.length >>> 0; 10 let accumulator = initialValue; 11 let k = 0; 12 // 如果第二个参数为undefined的情况下 13 // 则数组的第一个有效值作为累加器的初始值 14 if (accumulator === undefined) { 15 while (k < len && !(k in O)) { 16 k++; 17 } 18 // 如果超出数组界限还没有找到累加器的初始值,则TypeError 19 if (k >= len) { 20 throw new TypeError('Reduce of empty array with no initial value'); 21 } 22 accumulator = O[k++]; 23 } 24 while (k < len) { 25 if (k in O) { 26 accumulator = callback.call(undefined, accumulator, O[k], k, O); 27 } 28 k++; 29 } 30 return accumulator; 31} 32

最近更新时间:2021-07-07

赞赏支持

预览

题库维护不易,您的支持就是我们最大的动力!