Map and Set Flashcards
_____are used for storing keyed collections.
______are used for storing ordered collections.
Objects
Arrays
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows_______
keys of any type.
unlike objects, keys are not converted to ______
unlike objects, keys are not converted to strings
creates the map
new Map()
The method sets and stores the value by the key.
map.set(key, value)
returns the value by the key, undefined if key doesn’t exist in map.
map.get(key) –
returns true if the key exists, false otherwise.
map.has(key)
removes the element (the key/value pair) by the key.
map.delete(key) –
removes everything from the map
map.clear()
returns the current element count.
map.size
Map can also use objects as _____
keys
let john = { name: “John” };
let visitsCountMap = new Map();
set map to return below
alert( visitsCountMap.get(john) ); // 123
visitsCountMap.set(john, 123);
For looping over a map, there are 3 methods:
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.
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
}
let recipeMap = new Map([
[‘cucumber’, 500],
[‘tomatoes’, 350],
[‘onion’, 50]
]);
// iterate over values (amounts)
for (let amount of recipeMap.values()) {
alert(amount); // 500, 350, 50
}