[英]can not get the correct array length
The code below returns the length of an array 下面的代码返回数组的长度
var test=[];
test["abc"]=1;
test["abcd"]=11;
console.log(test.length);
I expected it outputs 2 but it displays 0 我期望它输出2但它显示0
Your comment welcome 欢迎您发表评论
You aren't actually adding any elements to the array, this is creating properties on the array object. 您实际上并没有在数组中添加任何元素,而是在数组对象上创建属性。
You can tell that I am saying the truth by typing this: 您可以通过键入以下内容来表明我说的是事实:
console.log(test.abc);
console.log(test.abcd);
The length
would have been increased probably if you had added the elements using push()
or set them using a numerical index like: 如果您使用
push()
添加了元素或使用了像这样的数字索引来设置元素,则length
可能会增加:
test[0] = 1;
test[1] = 2;
You should count the number of keys using Object.keys
: 您应该使用
Object.keys
计算键的数量:
console.log(Object.keys(test).length); // 2
Ideally, don't use array but a plain JavaScript object (also called hash ): 理想情况下,不要使用数组,而要使用普通的JavaScript对象(也称为hash ):
var test = {};
test.abc = 1;
test.abcd = 11;
Your problem is due to a misunderstanding of what consitutes and array in Javascript. 您的问题是由于对Java脚本的组成和数组有误解。
In Javascript, an array
is specified as a specific type of object, consisting of only numeric keys. 在Javascript中,将
array
指定为特定类型的对象,仅由数字键组成。
The .length
is a special property of the array object, which is tied to the value of the largest numeric key in the array. .length
是数组对象的特殊属性,该属性与数组中最大数字键的值相关。
By using keys such as "abc"
, you are in fact merely setting arbitrary properties on the object; 实际上,通过使用诸如
"abc"
键,您实际上只是在对象上设置了任意属性。 the length
property will be completely unaffected by this. length
属性将完全不受此影响。
You have two options: 您有两种选择:
Use numeric keys for your array. 对数组使用数字键。
If you need to use named keys, you will have to accept that the length
property and other array-specific features are not available. 如果需要使用命名键,则必须接受
length
属性和其他特定于阵列的功能不可用。 So you may as well use a regular object rather than an array. 因此,您也可以使用常规对象而不是数组。
It is still possible to count the elements in an object, but it's not as simple as just using a length
property. 仍然可以对一个对象中的元素进行计数,但是它并不像仅使用
length
属性那样简单。
If you want to add items to the array use 如果要将项目添加到数组中,请使用
array[0] = 1;
array[1] = 11;
Otherwise you are adding properties to the array 否则,您将向数组添加属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.