简体   繁体   English

在JS数组中使用字符串键分配值的方式和方式为何?

[英]How and why does assigning values with string keys work in JS arrays?

See this code: 参见以下代码:

 var arr = []; arr.foo = 'bar'; console.log(arr.foo); 

Now, we see that arr.foo doesnt throw an error and works, but technically it should throw an error so why doesn't it? 现在,我们看到arr.foo不会引发错误并且可以工作,但是从技术上讲它应该引发错误,所以为什么不这样做呢?

Also, how is the above represented in memory, considering array blocks are mostly allocated memory in continuous location with the index of the offset, how does that work here? 另外,上述内容如何在内存中表示,考虑到数组块大多是在连续位置分配了带有偏移索引的内存,这在这里如何工作?

...technically it should throw an error... 从技术上讲它应该抛出一个错误

No, it works entirely as described in the specification . 不,它完全按照规范中的描述工作。

It works because standard JavaScript arrays aren't really arrays ,* they're just objects backed by Array.prototype with a special length property and special handling for property names that are array indexes according to the specification. 之所以可以使用它,是因为标准的JavaScript数组并不是真正的数组 ,*只是由Array.prototype支持的对象,具有特殊的length属性和对根据规范作为数组索引的属性名称的特殊处理。 A property with any other name is just a normal object property, not an array entry. 具有任何其他名称的属性只是普通的对象属性,而不是数组条目。

Since arrays are objects, they can have non-array-entry properties, just like any other object. 由于数组是对象,因此它们可以具有非数组输入属性,就像其他任何对象一样。

FWIW, the definition of an array index is: FWIW,数组索引的定义是:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 2 53 -1. 整数索引是一个字符串值的属性键,它是规范的数字字符串(请参见7.1.16),其数值为+0或正整数≤2 53 -1。 An array index is an integer index whose numeric value i is in the range +0 ≤ i < 2 32 -1. 数组索引整数索引,其数值i在+0≤i <2 32 -1的范围内。

Note that typed arrays are true arrays; 注意, 类型化数组是真实数组; but they're also objects, and you can add non-array-entry properties to them, too. 但是它们也是对象,您也可以向它们添加非数组输入属性。


* (that's a post on my anemic little blog) * (这是我贫乏的小博客上的帖子)

Arrays are Objects and you can put inside different kinds of objects like strings, like dictionaries, another objects in general etc. when you write: 数组是对象,您可以在编写时将不同种类的对象放入字符串之类的对象中,例如字典,字典,其他一般对象等。

arr.foo="bar"

you are puting a value "bar" for the name access foo. 您正在为名称访问foo输入值“ bar”。 your variable arr is now 您的变量arr现在是

 arr={foo:"bar"}

and you can access it like you did arr.foo if you want more information check te page from the w3c here https://www.w3schools.com/js/js_arrays.asp in the section array object. 你可以,如果你想从这里W3C的更多信息检查TE页像你这样arr.foo访问https://www.w3schools.com/js/js_arrays.asp在部分数组对象。

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

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