fe-interview
fe-interview copied to clipboard
手动实现 Array.prototype.reduce 函数?
Array.prototype._reduce = function(callback /*, initialValue*/) {
if (this == null) {
throw new TypeError('null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError('callback is not a function');
}
const oldArr = Object(this); // 保存一份原数组
const len = oldArr.length >>> 0; // 原数组的长度
let initialValue, k=0;
// 处理初始累积值
if(arguments.length >= 2) {
initialValue = arguments[1];
} else {
while(k < len && !(k in oldArr)) k++;
if(k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
initialValue = oldArr[k++];
}
// 遍历老数组剩下的元素
while(k < len) {
if(k in oldArr) {
initialValue = callback(initialValue, oldArr[k], k, oldArr);
}
k++;
}
return initialValue;
}
const array = [1, 2, 3, 4, 5];
// var array = []
array._reduce(function(acc, cur, index, arr) {
return acc + cur;
}, 100)