map() and reduce() are both methods that can process arrays, but their uses are slightly different. The biggest difference is that map() can generate some processing results as new arrays. This article Let’s take a look at the detailed content of the article.
For example, if you want to create a new array that doubles the numbers stored in the array, you can write it as follows.
var numbers = [1,2,3,4,5]; var result = numbers.map(function(num) { return num * 2; }) console.log(result);
The running result is
In this example, map() will be performed on an array containing numeric values.
You can see that each element of the array is returned 2 times within the function.
From this, the execution result shows that an array with twice the original value can be generated.
Strictly speaking, it's not possible to do the same thing using reduce(), but if you use map(), you can do it efficiently with a very simple description.
Regarding the use of the reduce() method, you can refer to: How to use reduce() in JavaScript
The above is the detailed content of What is the difference between map() and reduce() in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!