Let's create a MyMap class so that it doesn't hide the actual Map class in JS. We'll create a container object that'll keep track of all our values that we add to the map. We'll also create a display function that prints the map for us.
Example
class MyMap { constructor() { this.container = {}; } display() { console.log(this.container); } }
In ES6, you can directly create a dictionary using the Map class. For example,
Example
const map1 = new Map(); const map2 = new Map([ ["key1", "value1"], ["key2", "value2"] ]);
Checking if a key existing
We need to define the hasKey method so that we can check if a key is already there. We will use this method while removing elements and setting new values.
Exaample
hasKey(key) { return key in this.container; }
In ES6, you can check if a key exists in a map using the has method. For example,
Example
const myMap = new Map([ ["key1", "value1"], ["key2", "value2"] ]); console.log(myMap.has("key1")) console.log(myMap.has("key3"))
Output
This will give the output −
True False