JS 实现reduce
Array.prototype.reduceArr = function (fn, initValue) {
if (Object.prototype.toString.call(fn) !== "[object Function]") {
throw new Error('current params is not correct')
}
let arr = this;
let initIndex;
let acc;
initIndex = arguments.length === 1 ? 1 : 0;
acc = arguments.length === 1 ? arr[0] : initValue;
for (let i = initIndex; i < arr.length; i++) {
acc = fn(acc, arr[i], i, arr);
}
return acc;
}
let arr = [1, 2, 3, 4, 5]
let res = arr.reduceArr((pre, cur) => { return pre + cur; }, 10)
console.log(res)
附录:参考来源

浙公网安备 33010602011771号