使用jQuery的javascript关联数组长度 [英] javascript associative array length using jQuery

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

问题描述

我正在使用javascript关联数组,如:

I am using javascript associative array like:

var testarray = [];
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

我也在使用jquery。如何使用jquery或任何其他方法检查此关联数组的长度?基本上我想检查这个数组是否为空。

I am also using jquery alongside. How can I check length of this associative array using jquery or any other method? Basically i want to check whether this array is empty or not.

谢谢。

推荐答案

你不应该使用数组来存储非数字索引,你应该使用一个简单的对象:

You shouldn't use an array to store non-numeric indexes, you should use a simple object:

function getObjectLength (o) {
  var length = 0;

  for (var i in o) {
    if (Object.prototype.hasOwnProperty.call(o, i)){
      length++;
    }
  }
  return length;
}

编辑:因为你正在使用jQuery而你想要检查对象是否为空,1.4版本引入了 $。 isEmptyObject

Since you are using jQuery and you want to check if the object is "empty", the 1.4 version introduced the $.isEmptyObject

if ($.isEmptyObject(obj)) { 
  //...
}

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

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