Let’s study JavaScript Maps.
Maps are just like objects.
They retailer the weather in a key/worth pair.
Nevertheless, a map can comprise objects, capabilities, and different knowledge varieties as a key, not like objects.
We are able to create a Map utilizing the brand new Map() constructor.
To insert it into the map, we use the set() methodology. We are able to use objects and capabilities as keys as properly.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
console.log(map1)
//anticipated output: Map {"a": 1, "b": 2}
To entry the weather, we use the get() methodology. We name the get methodology on the important thing and get the corresponding values.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
console.log(map1.get('a'));
// anticipated output: 1
To examine if a component is current within the map, we get a operate known as has()
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
console.log(map1.has('c'))
//anticipated output: false
Then we’ve clear() and delete() strategies which may allow us to take away knowledge from the map
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.delete('b');
console.log(map1)
//anticipated output: Map {"a" : 1}
To get the size of the Map we’ve the property of dimension which can give us the variety of components current on the map.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
console.log(map1.dimension);
// anticipated output: 3
To iterate over the map, we will use for loops or for-each loop. The weather are accessed within the order they’ve been inserted.
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
for (let [key, value] of map1){
console.log(key, "-", worth)
}
// a - 1
​// b - 2
​// c - 3
map1.forEach(operate(worth, key){
console.log(key + "-" + worth)
})
// a-1
​// b-2
​// c-3
We are able to iterate over the keys and values individually as properly.
for(let values of map1.values()){
console.log(values)
}
//1 2 3
for(let values of map1.keys()){
console.log(values)
}
//a b c
That was a fast overview of the Map object.
Let me know in case you have used it in sensible utility and the way did it carry out!