Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Why for .. in gets all the properties, but for .. of doesn't get all the values?

I tested the following code:

arr = [3, 5, 7];

arr.foo = "hello";

arr["boo"] ="moo"


for (i in arr) {
   console.log(i);
}

for (i of arr) {
   console.log(i); 
}

for .. in gets all the properties of the array.

for (i in arr) {
   console.log(i); 
}

returns:

0 
1 
2 
foo 
boo

but for .. of doesn't get all the values

  for (i of arr) {
       console.log(i); 
    }

returns:

3
5
7

What is the technical reason for this difference and why was this apparent inconsistency accepted as default behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...