Loading lessons...
Set and Map Methods
Set and Map Methods
Here are the most useful Set and Map methods together.
Set methods
const s = new Set();
s.add("x"); // add a value
s.has("x"); // true
s.delete("x"); // remove a value
s.clear(); // remove everything
s.size; // how many values
Map methods
const m = new Map();
m.set("a", 1); // add a pair
m.get("a"); // 1
m.has("a"); // true
m.delete("a"); // remove a pair
m.clear(); // empty the map
m.size; // how many pairs
Iterating a Map
m.forEach(function(value, key) {
console.log(key + " = " + value);
});
Iterating a Set
s.forEach(function(value) {
console.log(value);
});
Keys and values of a Map
m.keys(); // the keys
m.values(); // the values
m.entries(); // key-value pairs
TL;DR
- Sets: add, has, delete, clear, size.
- Maps: set, get, has, delete, clear, size.
- forEach iterates both.
- Maps expose keys(), values(), entries().