简体   繁体   中英

Why can't I use for in loop on a map object

For my own benefit I am going through each of the built in structured objects in Javascript and in particular I am trying out each of the basic 'for' loops so that I have grokked what works where.

In the case of Map, I noticed that the for/in loop is silent. I would have expected it to return the key values for each entry into the map.

 let map = new Map([[1, 1], ["two", "two"]]); map.set("three", 3); // Instead of add console.log(`map has three = ${map.has("three")}`); console.log(`map has size ${map.size}`); // no 'for loop' because map uses keys instead of index numbers for (let key in map) console.log(`for key ${key} in map ${map}`); // <<< This does not return?? for (let value of map) console.log(`for ${value} of ${map}`); map.forEach((value, key, localScopeCopyOfMap) => console.log(`forEach value ${value} in map ${[...localScopeCopyOfMap]}`));

Why does this not return anything?

for...in iterates over enumerable properties of an object. The keys in a map are not enumerable properties (though a map, like all objects, can have enumerable properties). For one thing, they can be of any type, not just strings, as with JavaScript objects, which have historically stood in for maps.

for...of iterates over an iterable , which is how the Map yields up its keys/values for iteration.

On this statement...

 for (let key in map) console.log(`for key ${key} in map ${map}`); // <<< This does not return??

Your comment "does not return" doesn't really make sense. None of these "return", they invoke a block zero or more times. In this case, zero, because the map has no enumerable properties.

If you do map.foo = "bar" , then for...in will iterate once, and print out "for key foo in map [object Map]" . This is not the same as inserting a new key/value pair into the map: It defines a new property on the object which exists completely separately from the map's contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM