let myReduce = function () {
let calback: any, hasParams: any;
if (!Array.isArray(this)) {
throw "myReduce must be called on an array";
}
if (typeof arguments[0] !== "function") {
throw "myReduce must be called on an function";
}
switch (arguments.length) {
case 0:
return;
case 1:
calback = arguments[0];
hasParams = false;
break;
case 2:
calback = arguments[0];
hasParams = arguments[1];
break;
}
let index = 0;
let pre = hasParams !== false ? hasParams : this[index];
let init = pre;
while ((hasParams !== false ? index : index + 1) < this.length) {
let next =
hasParams !== false
? this[index]
: index + 1 < this.length
? this[index + 1]
: null;
init = calback(init, next, index, this);
index++;
}
return init;
};
Array.prototype.myReduce = myReduce;
reduce实现
最新推荐文章于 2024-07-11 20:55:36 发布