考虑以下代码:
var arr = [];
arr["abc"] = 1;
arr["bcd"] = 2;
console.log(arr.length); // outputs 0
arr["1"] = "one"; // notice the subscript content is in quotes
console.log(arr.length); // outputs 2
console.log(arr); // outputs [undifined, "one"]
console.log(arr["abc"]); // outputs 1
在上面的程序中,我定义了数组arr
,它首先被分配了字符串索引,所以数组长度保持为0。我在某处看到当字符串值用于下标时,数组对象被视为普通对象。所以,我可以理解长度是否为零(应该是未定义的)。
然后,当我使用"1"
的下标时,应该是string类型的下标被当作Number,长度增加。然后,当打印数组时,索引 0
的值为 undefined,索引 1
的值为 "one"
(请注意索引 "abc"
和 "bcd"
在打印时不显示。
最后,当我尝试访问 "abc"
值时,我得到了该值。
所以我的问题如下:
- What happens when an array is assigned with a string index and why does the length remain the same?
- Does the javascript interpreter tries convert the index to a Number before using it?
- Where are the values of the array string indexes stored and why are they not shown when I try to print the array?
- Finally, can someone point me to a good article which explains the implementation details of javascript's features.
提前致谢。
最佳答案
这是一个有趣的问题。 JavaScript 以类似的方式处理数组和结构。
var arr = [];
这创建了一个新变量并将其设置为一个空数组。
arr["abc"] = 1;
这为 arr
创建了一个名为 abc
的属性,并为其赋值 1。arr
现在是一个具有用户定义属性的数组.
arr["bcd"] = 2;
这创建了 arr
的第二个属性,称为 bcd
并为其赋值 2。arr
现在有两个用户定义的属性。
console.log(arr.length); // outputs 0
数组仍然没有任何元素,所以它的长度为零。
arr["1"] = "one"; // notice the subscript content is in quotes
“1”的计算结果为一个整数,并且由于 arr
是一个数组(虽然它有一些用户定义的属性),它将“一”分配给第二个(从零开始的)元素数组。
console.log(arr.length); // outputs 2
arr[0]
不存在,但索引 1 存在,因此数组的长度为 2。
console.log(arr); // outputs [undefined, "one"]
没有为索引 0 提供定义。
console.log(arr["abc"]); // outputs 1
现在我们正在访问用户定义的属性。
感谢Peter Flannery用于提供指向 MDN's documentation 的链接对此。
关于javascript - Javascript如何存储数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28882625/