JS object itself is a key-value structure, ES6 why also need to add map, it and ordinary JS object What is the difference?
One, Map
1. Map Builder
First look at the simple use of map
string as key, and JS object similar to
var map = new map ()
//Set
map.set (' name ', ' John ') map.set (' Age ', ')
//Get
map.get (' name ')//John
map.get (' age ')//29
So on the code, it does not look like the JS object is concise
But the power of map is that its key can be any type
Object as key demo
var xy = {x:10, y:20} //coordinate
var wh = {w:100, h:200}//Width high
var map = new map ()
// Set
map.set (xy, ' coordinates ')
map.set (WH, ' width high ')
//Get
map.get (XY)//' coordinates '
map.get (WH)//' Width high '
The above shows a map with objects as key. The following is a diagram
The map constructor also supports array-passing methods
var map = new Map ([["Name", "John"], ["Age", "]"])
//Traversal key for
(Var key of Map.keys ()) {
Console.log (key )//Name, age
}
2. Iteration
Iterate over the map with for of, as set, the key calls Map.keys (), the value calls Map.values (), and the key-value entity calls Map.entries ()
var map = new map ()
//Set
map.set (' name ', ' John ')
map.set (' age ', ')
//Get
map.get (' name ')//' John '
map.get (' age ')//I
//traversal key for
(Var key of Map.keys ()) {
Console.log (key)
}
// Traversal value for (
var val of Map.values ()) {
Console.log (val)
}
//Traversal entity for
(Var arr of map.entries ( ) {
console.log (' key: ' + arr[0] + ', value: ' + arr[1])
}
///Iterate through the entity's shorthand for
(var [key, Val] of Map.entr IES ()) {
Console.log (' key: ' + key + ', value: ' + Val ')
}
3. Methods and properties
Second, Weakmap
The difference from map
Values of the base type are not accepted as key names
No keys, values, entries, and size
There are the following methods
The above mentioned is the entire content of this article, I hope you can enjoy.