Iterating maps
suggest changeA Map has three methods that return iterators: .keys(), .values(), and .entries(). .entries() is the default iterator. Each entry is a [key, value] pair, in insertion order.
const map = new Map([[1, 2], [3, 4]]);
for (const [key, value] of map) {
console.log(`key: ${key}, value: ${value}`);
// logs:
// key: 1, value: 2
// key: 3, value: 4
}
for (const key of map.keys()) {
console.log(key); // logs 1 and 3
}
for (const value of map.values()) {
console.log(value); // logs 2 and 4
}
Map also has .forEach(). The first argument is the callback, and the optional second argument is this inside that callback. The callback receives value, then key, then the map. That is the opposite of the [key, value] order used by .entries().
const map = new Map([[1, 2], [3, 4]]);
map.forEach((value, key, theMap) => console.log(`key: ${key}, value: ${value}`));
// logs:
// key: 1, value: 2
// key: 3, value: 4
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents