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
- The callback functioncallbackThere are four parameters
- Total The cumulative value returned by each callback execution.
- Item currently needs to process values
- Index Index of the current value (optional)
- Arr Current array (optional)
- initialValueDefault value (Optional)
- If the transfer
initialValue
The 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. - Called in an empty array with no default value
reduce
complains
- If the transfer
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.