用jquery查找数组的长度(大小)

时间:2022-01-16 22:17:42

I think I'm going crazy. I have a simply question that I'm struggling with for some reason.

我想我要疯了。我有一个简单的问题,我正在为某种原因挣扎。

Why does the below return 'undefined'?

为什么下面的返回值是“undefined”?

var testvar={};
testvar[1]=2;
testvar[2]=3;
alert(testvar.length);

edit I originally typed testvar[1].length. I knew this to be an error. I meant testvar.length

编辑我最初输入的testvar[1].length。我知道这是个错误。我的意思是testvar.length

3 个解决方案

#1


70  

Because 2 isn't an array, it's a number. Numbers have no length.

因为2不是数组,它是一个数字。数字没有长度。

Perhaps you meant to write testvar.length; this is also undefined, since objects (created using the { ... } notation) do not have a length.

也许你想写testvar.length;这也是未定义的,因为对象(使用{…}符号)没有长度。

Only arrays have a length property:

只有数组具有长度属性:

var testvar = [  ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length);    // 3

Note that Javascript arrays are indexed starting at 0 and are not necessarily sparse (hence why the result is 3 and not 2 -- see this answer for an explanation of when the array will be sparse and when it won't).

请注意,Javascript数组从0开始索引,并不一定是稀疏的(因此,为什么结果是3而不是2),请参见这个答案,以解释数组何时将是稀疏的,何时不会出现的。

#2


4  

testvar[1] is the value of that array index, which is the number 2. Numbers don't have a length property, and you're checking for 2.length which is undefined. If you want the length of the array just check testvar.length

testvar[1]是数组索引的值,也就是2。数字没有长度属性,你检查的是2。未定义的长度。如果你想要数组的长度,只需检查testvar.length。

#3


1  

Integer has no method length. Try string

Integer没有方法长度。尝试字符串

var testvar={};
testvar[1]="2";
alert(testvar[1].length);

#1


70  

Because 2 isn't an array, it's a number. Numbers have no length.

因为2不是数组,它是一个数字。数字没有长度。

Perhaps you meant to write testvar.length; this is also undefined, since objects (created using the { ... } notation) do not have a length.

也许你想写testvar.length;这也是未定义的,因为对象(使用{…}符号)没有长度。

Only arrays have a length property:

只有数组具有长度属性:

var testvar = [  ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length);    // 3

Note that Javascript arrays are indexed starting at 0 and are not necessarily sparse (hence why the result is 3 and not 2 -- see this answer for an explanation of when the array will be sparse and when it won't).

请注意,Javascript数组从0开始索引,并不一定是稀疏的(因此,为什么结果是3而不是2),请参见这个答案,以解释数组何时将是稀疏的,何时不会出现的。

#2


4  

testvar[1] is the value of that array index, which is the number 2. Numbers don't have a length property, and you're checking for 2.length which is undefined. If you want the length of the array just check testvar.length

testvar[1]是数组索引的值,也就是2。数字没有长度属性,你检查的是2。未定义的长度。如果你想要数组的长度,只需检查testvar.length。

#3


1  

Integer has no method length. Try string

Integer没有方法长度。尝试字符串

var testvar={};
testvar[1]="2";
alert(testvar[1].length);