//reduce 实现原理
let arr = [2, 3, 4];
Array.prototype.myreduce = function (callback, item) {
let self = this,
i = 0,
result = item; //原型链上绑定方法则 this 指向就是当前调用者,及当前的数组 arr
isInit = typeof item === "undefiend" ? true : false;
if (!isInit) {
i = 1;
result = self[0];
}
if (!this.length && !isInit)
new TypeError(`Reduce of empty array with no initial value`);
if (typeof callback !== "function") throw `${callback} is not function`;
for (; i < self.length; i++) {
result = callback(result, self[i]);
}
return result;
};
console.log(arr.myreduce((a, b) => a + b, 0));
报告:手写完事
|