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

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

问题描述

我觉得我快疯了.我有一个简单的问题,由于某种原因我一直在苦苦挣扎.

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

为什么下面返回'undefined'?

Why does the below return 'undefined'?

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

edit 我最初输入的是 testvar[1].length.我知道这是一个错误.我的意思是 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 开始,不一定 sparse (因此为什么结果是 3 而不是 2——见 this answer 用于解释数组何时稀疏以及何时不稀疏).

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天全站免登陆