简体   繁体   English

为什么我不能在 map object 上使用 for in 循环

[英]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.为了我自己的利益,我正在浏览 Javascript 中的每个内置结构化对象,特别是我正在尝试每个基本的“for”循环,以便我了解什么在哪里起作用。

In the case of Map, I noticed that the for/in loop is silent.在 Map 的情况下,我注意到 for/in 循环是无声的。 I would have expected it to return the key values for each entry into the map.我原以为它会返回 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. for...in迭代 object 的可枚举属性。 The keys in a map are not enumerable properties (though a map, like all objects, can have enumerable properties). map 中的键不是可枚举属性(尽管 map 与所有对象一样,可以具有可枚举属性)。 For one thing, they can be of any type, not just strings, as with JavaScript objects, which have historically stood in for maps.一方面,它们可以是任何类型,而不仅仅是字符串,例如 JavaScript 对象,它们在历史上代表地图。

for...of iterates over an iterable , which is how the Map yields up its keys/values for iteration. for...of迭代一个iterable ,这就是Map产生其迭代的键/值的方式。

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.在本例中为零,因为 map 没有可枚举的属性。

If you do map.foo = "bar" , then for...in will iterate once, and print out "for key foo in map [object Map]" .如果您执行map.foo = "bar" ,那么for...in将迭代一次,并打印出"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.将新的键/值对插入 map 不同:它在 object 上定义了一个新属性,该属性与地图内容完全分开存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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