This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
In this article, we will continue to learn more about reduce(), which is related to JavaScript arrays.
Here are some amazing “small-bugs” that learn that JavaScript isn’t perfect but doesn’t affect how it works:
JavaScript high order reduce()
.reduce() and map() can be thought of as higher-order functions that take a function as an argument to operate on each element of the array traversal. However, the different operations and parameters during iteration make the functional usage of reduce() relatively advanced.
Mdn-array.prototype.reduce () : The reduce() method performs a reducer function (in ascending order) provided by you on each element in the Array, summarizing its results into a single return value.
Syntax and parameters of reduce() method
The higher-order -reduce() function takes four arguments:
Attention!!!!! Note the difference between map() and map()
- Accumulator (
acc
) (Accumulator) - Current Value (
cur
) (Current value) - Current Index (
idx
) (Current index) - Source Array (
src
(Source array)
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
// The return value of the reduce method is assigned to the accumulator, which is remembered in each iteration of the array,
// and finally becomes the final single result value.
Copy the code
Reduce () computes the result cumulative with the next element in the sequence
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
Copy the code
reduce() usage
A simple use: reduce makes array summation writing easier
let arr = [1.2.3.4.5.6.7.8.9]
arr.reduce(function (x, y) {
return x + y
})
/ / and 45
Copy the code
What values do the parameters of the method function passed to reduce() represent?
List of related reading articles
- JavaScript Learning – Function remaining arguments
- JS small problem learning – function optional argument
- JS imperfect can also run – auto add semicolon (;) The problem,
- JS imperfect can also run – array object addition problem,
- JS imperfect arrow function correlation (2),
- JS is not perfect
- JavaScript Higher-order functions (1)
- JavaScript higher-order functions – the array map() method
Refer to the article
- MDN –
Array.prototype.reduce()