javascript的reduce简单实现原理
Array.prototype.myReduce = function (callback, prev) {
for (let i = 0; i < this.length; i++) {
if (typeof prev === "undefined") {
prev = callback(this[i], this[i + 1], i + 1, this);
i++;
} else {
prev = callback(prev, this[i], i, this);
}
}
return prev;
};
let sum = [1, 2, 3, 4].myReduce((a, b, index, arr) => {
return a + b;
});
console.log(`sum`, sum);

浙公网安备 33010602011771号