简体   繁体   English

Javascript:将键值对添加到数组

[英]Javascript: adding a key-value pair to array

I noticed that I can add a key value pair to an array (not an object, an array). 我注意到我可以将键值对添加到数组(而不是对象,数组)。

var a = [];       // create the array
a[0] = "test";    // conventionally setting an index of 0 to a value
a["foo"] = "bar"; // this actually sets a "key" of the array to "bar"

If I try to get the value of a.foo or `a["foo"], I simply get "bar". 如果我尝试获取a.foo或`a [“ foo”]的值,我只会得到“ bar”。 No errors raised. 没有提出错误。

I know that a Javascript Array is actually an object, but with special rules, but it feels weird that this doesn't throw an error. 我知道一个Javascript数组实际上是一个对象,但是有特殊的规则,但是感到奇怪的是,它没有引发错误。

I'm using the latest version of Chrome. 我正在使用最新版本的Chrome。

Is there an actual use case where this is ok to do? 是否有可以使用的实际用例? What is common practice around this fact? 围绕这个事实有什么惯例?

Now try this: 现在尝试这个:

> Object.getOwnPropertyNames(a)
[ '0', 'length', 'foo' ]
> a.length
1

Welcome to JavaScript! 欢迎使用JavaScript! It's such a wonderful place... 这是一个很棒的地方...

Yes, you can create named properties on an array. 是的,您可以在数组上创建命名属性。 No, you probably shouldn't. 不,您可能不应该。 They won't be counted in Array.length , and most developers who read your code will be experiencing a moment of confusion that is unlikely to lead to a positive outcome. 它们不会被计入Array.length ,并且大多数阅读您的代码的开发人员都将经历一时的混乱,这不太可能导致积极的结果。

If you need a named property, use a (non-array) object. 如果需要命名属性,请使用(非数组)对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM