问题描述
我正在深入研究&对象原型(您不知道JS),我发现这件棘手的事令我震惊:
I am digging into this & Object prototype (You Don't Know JS) and I found this tricky thing that blew my mind:
我创建了一个文字数组(JS数组是对象) x = ['foo',42,'bar']
并添加了一个名为baz的属性,如 x.baz ='baz'
。然后,在Chrome开发者控制台中,只需键入 x 即可显示以下结果:> (3)[ foo,42, bar,baz: baz]
。如果我展开 >
,则数组的每个值都有其自己的键,例如:
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
我创建了哪种 JS-object-monster ? For和forEach循环不计算 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!
推荐答案
这不是怪物。就像其他数组一样,它只是一个JS对象。向JS数组添加属性不是不可以...可以。一个很好的理由是简单地以一种包含的方式在数组内携带状态。从功能上来说,这在像JS这样的非常松散类型的语言中是正确的。如果选择执行此操作,则还必须采取预防措施,以免被 for
循环弄糊涂。
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.
这篇关于for和forEach绕过Array属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!