我在练习JavaScript数组时,遇到了这种情况。当我使用数值声明数组属性并尝试获取数组的长度时,它会显示长度。但是当我使用字符值设置数组的属性时,我得到的数组长度为零。为什么会发生这种情况?
var array_1 = [];
var array_2 = [];
array_1[0] = "Hello World 1";
array_1[1] = "Hello World 2";
array_1[2] = "Hello World 3";
array_2['abc'] = "Hello World";
array_2['def'] = "Hello World 1";
array_2['ghi'] = "Hello World 2";
console.log(array_1.length);
console.log(array_2.length);
最佳答案
您可以查看here :
the length property as well as array methods are only applied to the elements with numeric indexes. Therefore, elements added using string indexes can only be regarded as properties of the array object and not true array elements.
数组是 JavaScript 中的对象。因此,您可以认为将字符串键元素添加到数组中,就像向对象添加新属性一样。这就是为什么 length 只适用于添加了数字索引的数组元素。
基本上你可以认为array object是 javascript object 的扩展但具有诸如推送、删除或长度之类的属性,这些属性都是集合对象独有的。
查看以下示例以更好地了解不同场景下的用法:
var array = [];
array[0] = 1;
// Length = 1
console.log(array.length);
array["five"] = 5;
// Length still = 1
console.log(array.length);
array[1] = 1;
// Length now is = 2
console.log(array.length);
array[4] = 1;
// Length now is = 5, because you are adding an element to the position 4
console.log(array.length);
console.log(array);
关于javascript - 当我们使用字符值而不是数字定义一组数组属性时,为什么数组的长度显示为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60263938/