I was reading this example of using a for.. of
loop on a Map, and I was a bit confused with this syntax:
var myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (var [key, value] of myMap) { console.log(key + " = " + value); }
Specifically, I don't understand the array destructuring that is happening. I understand that you can use array destructuring to do something like let [one, two] = [1, 2];
, but what is happening in this example? myMap
isn't an array so why is this getting the correct values?
Another question I have is why is the order key, value
in the destructuring, but when you do a forEach()
the order is value, key
, like here:
myMap.forEach((value, key) => { console.log(key + " = " + value); });
for (var [key, value] of myMap) { console.log(key + " = " + value); }
is like
for (let pair of myMap) { var [key, value] = pair; console.log(key + " = " + value); }
So it’s not myMap
that has to be an array for the destructuring to work; rather, each of its elements has to be an array when it’s iterated over, and iterating over a map indeed produces arrays (key/value pairs).
Map#forEach
’s argument order is probably for consistency with Array#forEach
, which calls the function with arguments (item, index)
; it, in turn, probably does that because you don’t always need the index.
Slightly off topic but as an aside:
myMap.forEach((v,k) => {});
is about 50% more performant than
for (var [key, value] of myMap) { }
so perhaps consider using Map.prototype.forEach
(not to be confused with Array.prototype.forEach
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With