Make a summary every day, persistence is victory!
/** @date 2021-07-09 @description array.prototype.reduceCopy the code
One (sequence)
Array.prototype.reduce executes the passed function on each element of the Array, uses an accumulator to summarize the result, and returns the accumulator.
Reduce takes two parameters, a callback function and an initial value
The callback function takes four arguments:
- Accumulator: The value returned by each run of the callback function and the value returned at the end
- Current: indicates the current value
- Index: indicates the current index
- Source: source array
The initial value is the ACC passed in as the first call to the callback, and is optional. If not passed, the first value of the array is used as the initial value, and the first value of the array does not call the callback. Also, an error is reported when reducing is called on an empty array without passing the initial value.
Ii (Use)
Reduce can be used when you want to do something based on an array and then return a value, such as
Compute the array and:
const arr = [1, 2, 3, 4]; const sum = arr.reduce((acc, cur) => { return acc + cur; }); console.log(sum); / / 10Copy the code
Array deduplicating:
const arr = [1, 2, 3, 4, 1, 5, 4, 2, true, false, true, NaN, NaN, null, null, '', ''];
const newArr = arr.reduce((acc, cur) => {
if (!acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);
console.log(newArr); // [ 1, 2, 3, 4, 5, true, false, NaN, null, '' ]
Copy the code
I think using Reduce in development can be elegant and cup filling. If you are interested, you can master it. Take an example of myself. So use reduce as much as possible.
Three (handwriting implementation)
Today there was a question about implementing Reduce, but I didn’t choose it (I should have chosen it), so I went home and wrote:
Array.prototype.myReduce = function (callback, initVal) {const self = this; // declare the accumulator let acc; if (! InitVal) {if (self.length === 0) {// If (self.length === 0) Throw TypeError('Reduce of empty array with no initial value'); } // if initVal is not passed but the array has a value, the first acc is the first value of array acc = self[0]; If (self.length === 0) {acc = initVal; if (self.length == 0) {acc = initVal; } else {// call callback(initVal, self[0], 0, self); }} for (let I = 1; i < self.length; i++) { acc = callback(acc, self[i], i, self); } return acc; };Copy the code