for and forEach bypass Array property

2019-07-20 09:31发布

问题:

I am digging into this & Object prototype (You Don't Know JS) and I found this tricky thing that blew my mind:

I created a literal Array (JS Arrays are objects) x = ['foo', 42, 'bar'] and added a property called baz like x.baz = 'baz'. Then, in Chrome dev console, just typping x will display the following result: > (3) ["foo", 42, "bar", baz: "baz"]. If I unfold the ">", each value of the array has its own key like:

0: "foo"

1: 42

2: "bar"

baz: "baz"

What kind of JS-object-monster did I create? For and forEach loops do not count the baz property and bypass it.

Help would be very appreciated. Thank you!

回答1:

This is not a monster. It's just a JS object like any other array. Adding properties to a JS array is not a no no... You can. One good reason is to simple carry a state in a contained manner within the array. Functionally this is correct in a very loosely typed language like JS. If you chose to do this, then you also have to take precautions in order not to be bewildered in a for in loop, for instance.



回答2:

you just created an object and added a property. When you use the "for in" loop, you move on the properties of the instance of the object, not of those its prototype.

Don't worry, you haven't created a JS-object-monster! :)