手写reduce函数

reduce函数式es6中的数组方法,reduce可以实现一个数字数组的累加,或者redux中的compose redux中compose的实现原理

先来看一下它的使用

  • reduce有两个参数 第一个是一个回调函数callback
  • 第二个是可选参数,如果传了,会作为callback的第一个参数
  • callback中第一个参数:当存在reduce中的第二个参数时,则callback的第一个参数是reduce中的第二个参数,当不存在时,它是当前数组的第一项
  • callback中的第二个参数:遍历中的当前值
  • callback中的第三个参数:遍历中当前值的索引
  • callback中的第四个参数:当前遍历的数组
/**
 * 参数一:回调函数
 * 参数二:prev
 *
 * 回调函数中有四个参数  prev, current, index, arr
 *
 */
// 存在第二个参数
[1, 2, 3].reduce((prev, current, index, arr) => {
  console.log('prev', prev); // 100
  console.log('current', current); // 1
  console.log('index', index); // 0
  console.log('arr', arr); // [1, 2, 3]
}, 100);

// 不存在第二个参数
[1, 2, 3].reduce((prev, current, index, arr) => {
  console.log('prev', prev); // 1
  console.log('current', current); // 2
  console.log('index', index); // 1
  console.log('arr', arr); // [1, 2, 3]
});

并且reduce是Array原形中的方法,所以:

Array.prototype.reduce = function (callback, prev) { // 注意接下来要用到this, 所以这个地方不要写成 (callback,prev)=>{}
  for (let i = 0; i < this.length; i++) {
    if (prev === undefined) {
      prev = callback(this[i], this[i + 1], i + 1, this); // 没有传prev的时候  需要给prev赋值成当前数组里的第一项
      i++; // 赋值完之后  prev有值了  下一次应该从第2项开始
    } else {
      prev = callback(prev, this[i], i, this);
    }
  }
  return prev;
};

测试一下

// 传第二个参数
let n = [1, 2, 3, 4].reduce((a, b, c, d) => {
  return a + b;
}, 100);
console.log(n); // 110


// 不传第二个参数
let n = [1, 2, 3, 4].reduce((a, b, c, d) => {
  return a + b;
});
console.log(n); // 10

你可能感兴趣的:(手写系列,javascript,前端)