js 手撕Array.reduce

953 阅读1分钟

前言

自我学习手撕js代码,今天自己手撕一下Array.reduce方法。 每天学习一点。记录一下📝

MDN文档(reduce):

以下是自我理解:

reduce方法接受两个参数

  1. 回调函数callback参数有四个
    1. total 累加值,每次执行回调执行返回的值。
    2. item 当前需要处理值
    3. index 当前值索引 (可选)
    4. arr 当前数组 (可选)
  2. initialValue 默认值 (可选)
    1. 如果传递initialValue第一次从索引0开始 首次返回默认值,如果没有提供初始值,则将使用数组中的第一个元素。
    2. 在没有默认值的空数组调用reduce会报错

开始鲁代码

1.创建myReduce函数

2.挂载在Array原型上,this指向调用数组

reduce() 代码

// callback 回调函数
Array.prototype.myReduce = function (callback) {
  const initVal = arguments[1] ? arguments[1] : ""; // 获取默认值
  const len = this.length;
  if(!len && !initVal) { // 没有默认值并且空数组报错
    throw Error('Reduce of empty array with no initial value');
  }
  if(!len) return initVal; // 空数组不执行回调函数
  
  let total = initVal ? initVal : this[0]; // 是否有默认值,没有就取索引0的值
  
  let i = initVal ? 0 : 1;
  for(; i < len; i++) {
    total = callback(total, this[i], i, this); // 每次执行回调返回的值赋值给total
  }
  
  // 最后返回累加值
  return total;
}

下面我们运行看看结果(没有传递默认值):

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

const total = arr.myReduce(function(total, item, index, arr) {
  console.log(total, item, index, arr);
  return total + item;
  // expected results:  1, 2, 1, [1,2,3,4,5]
},);

console.log(total); // expected results 15

如图:

传递第二参数 有默认值:

 const total = arr.myReduce(function (total, item, index, arr) {
      console.log(total, item, index, arr);
      return total + item;
      // expected results:  1, 2, 1, [1,2,3,4,5]
    }, 10);

  console.log(total); // expected results 25
  

如图:

到这里就完成✅Array.reduce方法的实现。