Home>Article>Web Front-end> A thorough understanding of the Array.reduce method in js in one article
This article brings you relevant knowledge about js. It mainly talks about the Array.reduce method in js. Friends who are interested can take a look at it together. I hope it will be helpful to everyone.
We often use the reduce method of the Array object to do some calculations or data combinations. We find that after using reduce for so many years, it is not I know it well and just recently discovered that it works fine if we don't pass the initial value, and the array can also be an array of functions to enhance our code.
This article will take you back to understand Array.reduce and application scenarios.
Let’s take a look at how MDN describes it:
reduce()
The method executes areducerfunction provided by you in order for each element in the array. Each time thereduceris run, the calculation result of the previous element will be passed in as a parameter, and finally The results are summarized into a single return value.
Let’s take a look at this code:
const arr = [1, 2, 3] const initValue = 10; function reducer(previousValue, currentValue, currentIndex, arrryTarget) { return preValue + currentValue } arr.reduce(reducer, initValue) // res === 16
reduce will traverse the arr array. The reducer will be executed as many times as there are arrays. The parameters for each execution process (arrryTarget is the same, so it is meaningless, unless the original array is directly changed during the traversal process, so it is not considered here) are as follows:
#reducer Repeated execution |
previousValue |
currentValue |
##currentIndex
| return
|
---|---|---|---|---|
10
|
1
|
0
|
11
|
|
11 |
| 2
| 1
| 13
|
13 |
| 3
| 2
| 16
|
initialValuereducer, and the iterator will start executing from the second element (index 1 instead of 0)
That is When the reducer function is executed for the first time, there is no "last calculation result". The initial value is passed here, so the
function starts execution from the element with array index 0, that is,arr.length
is equal to thereducer
number of executions.But what if the initial value is not passed? Let's change the code:
const arr = [1, 2, 3] - const initValue = 10; function reducer(previousValue, currentValue, currentIndex, arrryTarget) { return preValue + currentValue } - arr.reduce(reducer, initValue) // res === 16 + arr.reduce(reducer) // res === 6
At this time, the reducer will only execute
arr.length - 1times. The parameters for each execution are as follows:
Repeated execution
| previousValue
| currentValue
| currentIndex
return |
|
---|---|---|---|---|
1 | ##2 |
1 |
3 |
Second execution |
##3
|
2
|
6
|
|
The above is the detailed content of A thorough understanding of the Array.reduce method in js in one article. For more information, please follow other related articles on the PHP Chinese website!