Javascript如何存储数组

ani*_*udh 3 javascript arrays

请考虑以下代码:

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
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,我已经定义了arr首先分配了字符串索引的数组,因此数组长度保持为0.我读到某处,当字符串值用于下标时,数组对象被视为普通对象.所以,我可以理解长度是否为零(可能是未定义的).

然后,当我使用下标时"1",应该将字符串类型作为数字并且长度递增.然后,当打印数组时0,索引1的值为undefined ,索引具有值"one"(请注意索引"abc"并且"bcd"在打印时不显示.

最后,当我尝试访问该"abc"值时,我得到了值.

所以我的问题如下:

  1. 在为数组分配字符串索引时会发生什么,为什么长度保持不变?
  2. 在使用之前,javascript解释器是否尝试将索引转换为数字?
  3. 存储数组字符串索引的值在哪里以及为什么在我尝试打印数组时它们没有显示?
  4. 最后,有人能指出我一篇很好的文章,解释了javascript功能的实现细节.

提前致谢.

Pau*_*owe 6

这是个有趣的问题.JavaScript以类似的方式处理数组和结构.

var arr = [];
Run Code Online (Sandbox Code Playgroud)

这创建了一个新变量并将其设置为空数组.

arr["abc"] = 1;
Run Code Online (Sandbox Code Playgroud)

这创建了一个arr被调用的属性,abc并为其赋值1. arr现在是一个具有用户定义属性的数组.

arr["bcd"] = 2;
Run Code Online (Sandbox Code Playgroud)

这创建了一个arr被调用的第二个属性,bcd并为其赋值2. arr现在有两个用户定义的属性.

console.log(arr.length); // outputs 0
Run Code Online (Sandbox Code Playgroud)

该数组仍然没有任何元素,因此其长度为零.

arr["1"] = "one"; // notice the subscript content is in quotes
Run Code Online (Sandbox Code Playgroud)

"1"计算为一个整数,因为它arr是一个数组(虽然它有一些用户定义的属性),它将"一"分配给数组的第二个(从零开始)元素.

console.log(arr.length); // outputs 2
Run Code Online (Sandbox Code Playgroud)

arr[0] 不存在,但索引1,所以数组长度为2.

console.log(arr); // outputs [undefined, "one"]
Run Code Online (Sandbox Code Playgroud)

没有为索引0提供定义.

console.log(arr["abc"]); // outputs 1
Run Code Online (Sandbox Code Playgroud)

现在我们正在访问用户定义的属性.

感谢Peter Flannery提供MDN文档的链接.