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);
posted @ 2021-12-08 17:46  jerry-mengjie  阅读(89)  评论(0)    收藏  举报