Essential Map Methods
Method | Description |
---|---|
new Map() | Creates a new Map |
set() | Sets the value for a key in a Map |
get() | Gets the value for a key in a Map |
delete() | Removes a Map element specified by the key |
has() | Returns true if a key exists in a Map |
forEach() | Calls a function for each key/value pair in a Map |
entries() | Returns an iterator with the [key, value] pairs in a Map |
new Map() Method
1// Create a Map with new Map()
2const cars = new Map([
3 ["audi", 4],
4 ["mercedes", 1],
5 ["bmw", 10]
6]);
get() Method
1// The get() method gets the value of a key in a Map
2cars.get("bmw"); // Returns 10
set() Method
1// Set Map Values
2cars.set("bugatti", 2);
3cars.set("ferrari", 3);
4
5// with set() method, you can also change existing Map values
6cars.set("audi", 7);
delete() Method
1// The delete() method removes a Map element
2cars.delete("audi");
has() Method
1// The has() method returns true if a key exists in a Map
2cars.has("mercedes");
size Property
1// The size property returns the number of elements in a Map
2cars.size;
forEach() Method
The forEach() method calls a function for each key/value pair in a Map
1// List all entries
2let text = "";
3cars.forEach (function(value, key) {
4 text += 'key:'+ key + ', value:' + value;
5})
entries() Method
The entries() method returns an iterator object with the [key, values] in a Map
1// List all entries
2let text = "";
3for (const x of cars.entries()) {
4 text += x;
5}