Map

A Map is a collection of key/value pairs. Keys and values of a Map can be of any data type. Key/value pairs are arranged in insertion order. A Map object is created using the Map constructor.

Here is an example, which demonstrates how to create a Map object and do various operations on it:

let map = new Map();
let o = {n: 1};
map.set(o, "A"); //
add
map.set("2", 9);
console.log(map.has("2")); //check if key exists
console.log(map.get(o)); //retrieve value associated with key
console.log(...map);
map.delete("2"); //delete key and associated
value
map.clear(); //delete everything
//create a map from iterable
object
let map_1 = new Map([[1, 2], [4, 5]]);
console.log(map_1.size); //number of
keys

The output is as follows:

true
A
[object Object],A 2,9
2

While creating a Map object from an iterable object, we need to make sure that the values returned by the iterable object are arrays, each of length 2; that is, index 0 is the key and index 1 is the value.

If we try to add a key that already exists then it's overwritten. Map objects also implement the iterable protocol and can therefore also be used as an iterable object. While iterating Maps using the iterable protocol, they return arrays with key/value pairs as you can see in the preceding example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.0