Suppose that there is a function f (x) =x2; the function is in an array [1,2,3,4,5,6,7,8,9], which is usually implemented by means of traversal.
function f (x) { return x * x; } var arr = [1,2,3,4,5,6,7,8,9]; var result = []; for (var i=0; i<arr.length; i++) {Result.push (f (arr[i)) }
This can be done, but we have a more elegant implementation.
function f (x) { return x * x;} var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9// [1, 4, 9, +, +, +, +, +, Bayi]
The map () method is defined in the JavaScript array, we call the map () method of array and pass in our own function, and we get a new array as the result. The map passes in the parameters F, which is the function itself.
So, map (), as a higher-order function, actually abstracts the arithmetic rules. So we can not only calculate the simple f (x) =x2, but also the arbitrary complexity of the function, such as the array of all the numbers into a string:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9// [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
The map method in JavaScript