myReduce实现
2021-07-15 本文已影响0人
织雪纱奈
Array.prototype.myReduce = function(reducer, initialValue) {
const hasInitial = arguments.length > 1;
let ret = hasInitial ? initialValue : this[0];
for (let i = hasInitial ? 0 : 1; i < this.length; i++) {
ret = reducer.call(undefined, ret, this[i], i, this);
}
return ret;
}
// 或者极简版本
Array.prototype.myReduce = function(reducer, initialValue) {
let ret = initialValue;
for (let i = 0; i < this.length; i++) {
ret = reducer(ret, this[i], i, this);
}
return ret;
}