for and forEach bypass Array property

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 00:35:14

问题


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! :)



来源:https://stackoverflow.com/questions/44291907/for-and-foreach-bypass-array-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!