Skip to content

Latest commit

 

History

History
25 lines (21 loc) · 597 Bytes

0330.md

File metadata and controls

25 lines (21 loc) · 597 Bytes

实现一个Array.prototype.reduce

Array.prototype.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Array.prototype.myReduce = function(callback, initialValue) {
  let accumulator = initialValue ? initialValue : this[0];
  for (let i = initialValue ? 0 : 1; i < this.length; i++) {
    let _this = this;
    accumulator = callback(accumulator, this[i], i, _this);
  }
  return accumulator;
};

// 使用
let arr = [1, 2, 3, 4];
let sum = arr.myReduce((acc, val) => {
  acc += val;
  return acc;
}, 5);

console.log(sum); // 15