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

How to define map in js

(*-*)浩
Release: 2019-05-24 14:50:36
Original
11620 people have browsed it

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

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

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

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!

Related labels:
js
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