Map
objects are collections of key-value pairs. A key in the Map
may only occur once; it is unique in the Map
‘s collection.
Main methods
Method | Description |
---|---|
new Map() | creates a new Map object |
map.set(key, value) | stores the value by the key |
map.get(key) | returns the value by the key, undefined if key doesn’t exist in map |
map.has(key) | returns true if the key exists, false otherwise |
map.delete(key) | removes the element (the key/value pair) by the key |
map.clear() | removes everything from the map |
map.size | returns the current element count |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 | let map = new Map(); map.set('1', 'str1'); // a string key map.set(1, 'num1'); // a numeric key map.set(true, 'bool1'); // a boolean key // remember the regular Object? it would convert keys to string // Map keeps the type, so these two are different: alert( map.get(1) ); // 'num1' alert( map.get('1') ); // 'str1' alert( map.size ); // 3 |
Note:
Althoughmap[key]
also works, e.g. we can setmap[key] = 2
, this is treatingmap
as a plain JavaScript object, so it implies all corresponding limitations (only string/symbol keys and so on).
So we should usemap
methods:set
,get
and so on.
Map can also use objects as keys.
Ex:
1 2 3 4 5 6 7 8 9 | let john = { name: "John" }; // for every user, let's store their visits count let visitsCountMap = new Map(); // john is the key for the map visitsCountMap.set(john, 123); alert( visitsCountMap.get(john) ); // 123 |
Instance methods
Method | Description |
---|---|
map.keys() | returns an iterable for keys |
map.values() | returns an iterable for values |
map.entries() | returns an iterable for entries [key, value] , it’s used by default in for..of |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | let recipeMap = new Map([ ['cucumber', 500], ['tomatoes', 350], ['onion', 50] ]); // iterate over keys (vegetables) for (let vegetable of recipeMap.keys()) { alert(vegetable); // cucumber, tomatoes, onion } // iterate over values (amounts) for (let amount of recipeMap.values()) { alert(amount); // 500, 350, 50 } // iterate over [key, value] entries for (let entry of recipeMap) { // the same as of recipeMap.entries() alert(entry); // cucumber,500 (and so on) } |
Objects vs Maps
Map | Object |
---|---|
Directly iterable | Not directly iterable |
Have a size property | Do not have a size property |
Keys can be any datatype | Keys must be Strings (or Symbols) |
Keys are ordered by insertion | Keys are not well ordered |
Do not have default keys | Have default keys |