Map is a collection of keyed data items, just like an Object
. But the main difference is that Map
allows keys of any type.
Maps Main Methods
new Map()
- creates the mapmap.set(key, value)
- stores value by keymap.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 value by the key.map.clear()
– clears the mapmap.size
– returns the current element count.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