查找jQuery的数组长度(大小) [英] Find length (size) of an array in jquery

查看:270
本文介绍了查找jQuery的数组长度(大小)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'?

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

修改我原本输入的testvar [1]。长度。我知道这是一个错误。我的意思是testvar.length

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

推荐答案

由于 2 不是一个数组,它是一个数字。数字有没有长度。

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

也许你的意思是写 testvar.length ;这也是不确定的,因为对象没有一个长度(使用 {...} 符号创建)。

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

只有数组的长度属性:

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

需要注意的是JavaScript数组是在 0 收录起始和不一定稀疏(因此结果是3而不是2 - 见<一href=\"http://stackoverflow.com/questions/614126/why-is-array-push-sometimes-faster-than-arrayn-value/614255#614255\">this回答为当阵列将是稀疏的解释,当它不会)。

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).

这篇关于查找jQuery的数组长度(大小)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆