Home  >  Article  >  Web Front-end  >  How to use Map object in JavaScript? What operations are there?

How to use Map object in JavaScript? What operations are there?

不言
不言Original
2019-01-09 16:01:2512836browse

This article will introduce you to how to create a Map object and how to use a Map object to add, obtain, delete and iterate, so let's take a look at the specific content.

How to use Map object in JavaScript? What operations are there?

First let’s take a look atHow to create a Map object?

Map objects are often easier to understand by creating associative arrays.

We first create an instance with new.

var map = new Map();

To add elements, we use the set() method.

map.set('name', 'Tom');

In this example, the string "Tom" value is added to "name".

By the way, you can also set the initial value as follows when creating an instance.

new Map([['name', 'Tom'], ['name', 'Jerry']]);

How to get and delete elements

For example, create a Map object like this:

var map = new Map();
  
map.set('name', 'Tom');
map.set('age', 18);

To get the " name" value, you can use the get() method. As shown below

console.log(map.get('name'));

By the way, if you execute "size", you can get the number of stored elements, and if you use has(), you can confirm whether there is any value.

console.log(map.size);
console.log(map.has('age'));

To delete an element, just specify the value of the element to be deleted in delete().

map.delete('name');
map.clear();

For Map objects, executing clear will delete all stored elements.

Iterative processing of Map objects

Normally, iteration is easy using the for-of statement, but the Map object provides useful properties.

For example, you can use key() to retrieve all "keys" of a stored element.

Please see the example below

for(var key of map.keys()) {
  console.log(key);
}

In this example, you can see that we use keys() to repeatedly process the keys stored in the Map object storage

So Map All keys of an object can be enumerated.

In addition, using values() will get all the values ​​this time.

for(var val of map.values()) {
  console.log(val);
}

This article ends here. For more exciting content, you can pay attention to the relevant tutorial columns of the php Chinese website! ! !

The above is the detailed content of How to use Map object in JavaScript? What operations are there?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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