You can create a Map by providing an array to the new Map()
constructor.
// Create a Map const fruits = new Map([ [“apples”, 500], [“bananas”, 300], [“oranges”, 200] ]); |
You can retrieve the value associated with a key in a Map by using the get() method.
// Create a Map const fruits = new Map([ [“apples”, 500], [“bananas”, 300], [“oranges”, 200] ]); |
You can obtain the value for a key in a Map using the get() method.
fruits.get(“apples”); |
You can add elements to a Map using the set()
method.
// Create a Map const fruits = new Map(); // Set Map Values fruits.set(“apples”, 500); fruits.set(“bananas”, 300); fruits.set(“oranges”, 200); |
The set() method can also be used to update existing values in a Map.
fruits.set(“apples”, 500); |
The size property returns the count of elements in a Map.
fruits.size; |
The delete() method removes an element from a Map.
fruits.delete(“apples”); |
The clear() method removes all elements from a Map.
fruits.clear(); |
The has() method returns true if a key is present in a Map.
fruits.has(“apples”); |
fruits.delete(“apples”); fruits.has(“apples”); |
The forEach() method calls a callback function for each key/value pair in a Map.
// List all entries let text = “”; fruits.forEach (function(value, key) { text += key + ‘ = ‘ + value; }) |