JS中如何实现reduce?

194 阅读1分钟
Array.prototype.myReduce = function (fn, initVal) {
  let len = this.length;
  if (len == 0 && initVal == undefined)
    throw new TypeError("Reduce of empty array with no initial value");
  let accumulator, i;
  if (initVal != undefined) {
    accumulator = initVal;
    i = 0;
  } else {
    accumulator = this[0];
    i = 1;
  }
  for (let i = initVal != undefined ? 0 : 1; i < len; i++) {
    accumulator = fn(accumulator, this[i], i, this);
  }
  return accumulator;
};