Home  >  Article  >  Web Front-end  >  How to define map in js

How to define map in js

(*-*)浩
(*-*)浩Original
2019-05-20 09:20:3411568browse

I have always used arrays and objects to define data models. When I was looking through ES6 syntax a few days ago, I suddenly discovered that there is a Map object that is particularly useful for operating key-value pairs, and the code is more concise and clear, which is great.

How to define map in js

Today, we will learn step by step what a Map object is, and introduce to you the properties and methods of the Map object in detail. I hope that everyone will find another way to solve problems in data manipulation in the future. This is a new data structure in ECMA 6.

Definition

The Map object saves key/value pairs and is a collection of key/value pairs. Any value (object or primitive) can be used as a key or a value. The Object structure provides "string-value" correspondence, and the Map structure provides "value-value" correspondence.

Syntax:

mapObj=new Map([iterable]);

iterable can be an array or other iterable object, whose elements are either key-value pairs or an array of two elements. Each key-value pair is added to a new Map. null will be treated as undefined.

Map instance

All Map instances will inherit from Map.prototype.

Example

Map objects are similar to objects and are also collections of key-value pairs, but the scope of "keys" is not limited to strings, and various types of values ​​(including objects) can be used as keys.

let a=new Map();
let b={p:'Hello World'};
a.set(b,"content");
a.get(b);				//"content"
a.has(b)				//true
a.delete(b)				//true
a.has(b)   				//false

As a constructor, Map can also accept an array as a parameter. The members of this array are arrays representing key-value pairs.

let map=new Map(['first','aaaaaa'],['second','bbbbbb']);;
map.size();				//2
map.has('first');		//true
a.get(b);				//'aaaaaa'
map.has('second');		//true
a.get(b);				//'bbbbbb'

The above is the detailed content of How to define map in js. 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