Detailed description of Map/WeakMap in ECMAScript6,
The JS object itself is a key-value structure. Why does ES6 need to add Map? What is the difference between it and common JS objects?
1. Map
1. Map Constructor
First, let's look at the simple usage of Map.
// String as the key, similar to the JS object var map = new Map () // setmap. set ('name', 'john') map. set ('age', 29) // getmap. get ('name') // Johnmap. get ('age') // 29
The code looks like no JS object is concise.
However, the strength of Map is that its key can be of any type.
// Demonstrate var xy = {x: 10, y: 20} as key // coordinate var wh = {w: 100, h: 200} // var map = new Map () // setmap. set (xy, 'coordinate ') map. set (wh, 'width and high') // getmap. get (xy) // 'coordinate 'map. get (wh) // 'width and high'
The preceding example shows the Map using an object as the key. The figure below shows
The Map constructor also supports array transmission.
Var map = new Map ([["name", "John"], ["age", "29"]) // traverses keyfor (var key of map. keys () {console. log (key) // name, age}
2. Iteration
Like Set, for of is used for iterative Map. The key calls map. keys (), the value calls map. values (), and the key value entity calls map. entries ()
Var map = new Map () // setmap. set ('name', 'john') map. set ('age', 29) // getmap. get ('name') // 'john' map. get ('age') // 29 // traverse keyfor (var key of map. keys () {console. log (key)} // traverse valuefor (var val of map. values () {console. log (val)} // traverses the object for (var arr of map. entries () {console. log ('key: '+ arr [0] +', value: '+ arr [1])} // shorthand for traversing an object (var [key, val] of map. entries () {console. log ('key: '+ key +', value: '+ val )}
3. Methods and attributes
Ii. WeakMap
Difference from Map
The value of the basic type is not accepted as the key name.
No keys, values, entries, and size
Use the following methods:
The above is all the content of this article. I hope you will like it.