Home > Web Front-end > Front-end Q&A > Does javascript have map?

Does javascript have map?

WBOY
Release: 2023-05-16 09:01:38
Original
744 people have browsed it

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]
Copy after login

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']
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template