The for (... in ...)
syntax is available for use on any object, and will iterate over all properties of that object. More technically, this loop will iterate over any property in the object that's internally defined with its [[Enumerbale]]
property set to true.
The for (... of ...)
syntax is new with ES6, and is specific to collections, rather than all objects. It provides a shorthand way to iterate over the elements of a collection, rather than having to use a plain for
or while
loop with an index. It will iterate in this manner over any the elements of any collection that has a [Symbol.iterator]
property.
This isn't an "inconsistency", they're two different operators intended to be used for two different purposes. I can understand how it might seem like doing something like arr["boo"] ="moo"
would add an element to the array -- since you can access the array's elements via a similar syntax, as in arr[0]
. But it's easy to confirm that those aren't the same in effect - with arr["boo"] ="moo"
you're creating a property that can also be accessed by arr.boo
, but attempting to access the elements of an array by, say, arr.0
would be a syntax error, because they aren't the same as properties.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…