preface

Self learning hand tear JS code, today their own hand tear Array. Reduce method. Study a little every day. For the record 📝

MDN Document (Reduce) :

Here is self-understanding:

The Reduce method takes two parameters

  1. The callback functioncallbackThere are four parameters
    1. Total The cumulative value returned by each callback execution.
    2. Item currently needs to process values
    3. Index Index of the current value (optional)
    4. Arr Current array (optional)
  2. initialValueDefault value (Optional)
    1. If the transferinitialValueThe default value is returned for the first time from index 0, and if no initial value is provided, the first element in the array is used.
    2. Called in an empty array with no default valuereducecomplains

Start Lu code

1. Create the myReduce function

2. Mounted on the Array prototype, this refers to the call Array

Reduce () code

// callback callback function
Array.prototype.myReduce = function (callback) {
  const initVal = arguments[1]?arguments[1] : ""; // Get the default value
  const len = this.length;
  if(! len && ! initVal) {// No default value and empty array error
    throw Error('Reduce of empty array with no initial value');
  }
  if(! len)return initVal; // Empty arrays do not perform callbacks
  
  let total = initVal ? initVal : this[0]; // If there is no default value, take the value of index 0
  
  let i = initVal ? 0 : 1;
  for(; i < len; i++) {
    total = callback(total, this[i], i, this); // Assign the value returned each time the callback is executed to total
  }
  
  // Finally returns the cumulative value
  return total;
}
Copy the code

Let’s run it to see the result (no default values are passed) :

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
Copy the code

As shown in figure:

Passing the second argument has a default value:

 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
  
Copy the code

As shown in figure:

This completes the implementation of the ✅ array.reduce method.