Maps
If sets are to an array, maps are to an object
It has a key and a value instead of just values
const dogs = new Map();
- Call .set() to add something
dogs.set('Woofer',3);
dogs.set('Bowwower',5);
- .has() to check key
dogs.has('Woofer');
-true
- .get() to get value
dogs.get('Woofer');
-3
- .delete() to remove item
dogs.delete('Woofer');
You can iterate over Maps in 2 ways:
1.Use a forEach loop
dogs.forEach((val,key)=>console.log(val,key));
-Gives us all dogs
2.Use a for of loop
for(const dog of dogs){
console.log(key,val);
}
//Can use destructing here
for(const [key,val] of dogs){
console.log(key,val);
}
-Gives us an array of dogs
dogs.clear();
Useful for Meta-data tracking
WeakMap
Setting to null gets garbage collected, just like WeakSet
If sets are to an array, maps are to an object
It has a key and a value instead of just values
const dogs = new Map();
- Call .set() to add something
dogs.set('Woofer',3);
dogs.set('Bowwower',5);
- .has() to check key
dogs.has('Woofer');
-true
- .get() to get value
dogs.get('Woofer');
-3
- .delete() to remove item
dogs.delete('Woofer');
You can iterate over Maps in 2 ways:
1.Use a forEach loop
dogs.forEach((val,key)=>console.log(val,key));
-Gives us all dogs
2.Use a for of loop
for(const dog of dogs){
console.log(key,val);
}
//Can use destructing here
for(const [key,val] of dogs){
console.log(key,val);
}
-Gives us an array of dogs
dogs.clear();
Useful for Meta-data tracking
We can use the object itself to get values instead of key strings
const clickCounts = new Map;
const buttons = document.querySelectorAll(‘button’);
buttons.forEach(button => clickCounts.set(button,0
button.addEventListener(‘click’, function(){
const val = clickCounts.get(this);
console.log(val);
clickCounts.set(this,val+1);
console.log(clickCounts);
});
));
WeakMap
Setting to null gets garbage collected, just like WeakSet
No comments:
Post a Comment