Js functions have three functions that are useful in specific scenarios: reduce (), map (), and filter (). Arrays often use push, join, indexOf, slice, and so on, but there is a method that we often ignore: reduce, this method is absolutely powerful. Next, let's use this article to study together. Introduction
Let's take a look at the official overview of this method: The reduce () method receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value.
You must be a bit confused as I do. In fact, reduce receives a callback function, which calls each item in the array until the end of the array.
Let's give an example.
Suppose I have an array where all numbers are placed. I want to calculate the total number of these numbers. Under normal circumstances, we will loop through and add them one by one. With reduce, we don't need to be so troublesome. We only need a line of code.
var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10
How does this method work?
Reduce accepts a function. The function has four parameters:
1. Last value;
2. Current value;
3. Index of the current value;
4. array;
Let's take the array above as an example and print out these parameters:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue;});
The result is:
After analyzing this result, this callback function has been called four times in total. Because the previusvalue is not found for the first time, it starts from the second entry of the array and ends with the end of the array.
Reduce has a second parameter. We can use this parameter as the first parameter when calling callback for the first time. In the preceding example, because there is no second parameter, it starts directly from the second item of the array, if we give the second parameter 5, the result is as follows:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue;},5);
The value of previusvalue called for the first time is replaced by the second parameter passed in. The function is called five times, that is, the length of the array.
Reduce can help us easily complete many things. In addition to accumulation, there is also a flattened two-dimensional array:
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b);}, []);// flattened == [0, 1, 2, 3, 4, 5]
Summary
I can think of these two commonly used ones for the time being, but there must be a lot to use. The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.
For more details about the reduce method of arrays in JavaScript, please follow the PHP Chinese network!