5.手写reduce

发布时间 2023-10-31 09:13:44作者: Jannik

我们首先先创建一个index.js的文件在文件中定义一个数组,就像这样

const arr = [1, 2, 3, 4, 5];

const res = arr.reduce(function (sum, item) {
  return sum + item;
});

console.log(res);

使用node index.js运行这段代码,我们可以看到输出的结果是
15
现在让我们来实现自己的reduce方法吧

const arr = [1, 2, 3, 4, 5];

Array.prototype.myReduce = function (fn, initValue) {
  for (let i = 0; i < this.length; i++) {
    initValue = fn(initValue, this[i], i, this);
  }
  return initValue;
};

const res = arr.myReduce(function (sum, item) {
  return sum + item;
}, 0);

console.log(res);