Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  39] [ 5]  / answers: 1 / hits: 30379  / 9 Years ago, mon, december 21, 2015, 12:00:00

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);
});

More From » dictionary

 Answers
5
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.


[#63994] Friday, December 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;