Home > Article > Web Front-end > Does javascript have map?
There is map() function in JavaScript, which is a higher-order function for arrays. The map() function accepts a function as a parameter, uses this function to operate on each element in the array, and finally returns a new array containing the result of executing the function on each element of the original array.
Using the map() function can conveniently perform operations such as conversion and calculation on the elements in the array.
The following is an example of using the map() function:
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(function(num) { return num * 2; }); console.log(doubledNumbers); // [2, 4, 6, 8, 10]
In the above code, we define a digital array numbers, and then use the map() function to perform Multiply by 2 and save the result in a new array doubleNumbers.
In addition, we can also pass in a context object this in the second parameter of the map() function to use the this keyword in the callback function.
Next let’s look at another example:
const names = ['Alice', 'Bob', 'Charlie']; const initials = names.map(function(name) { return name.charAt(0); }, this); console.log(initials); // ['A', 'B', 'C']
In this example, we define a name array names, and then use the map() function to extract the first letter of each name, And save the results in a new array initials. We also pass in a context object this through the second parameter for use in the callback function.
In general, the map() function in JavaScript is a very useful high-order function that can operate on each element in the array by passing in a callback function and return a new Arrays make processing array data easier.
The above is the detailed content of Does javascript have map?. For more information, please follow other related articles on the PHP Chinese website!