Javascript 使用jQuery的javascript关联数组长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2402193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:08:58  来源:igfitidea点击:

javascript associative array length using jQuery

javascriptjquery

提问by Prashant

I am using javascript associative array like:

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

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

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.

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

Thank you.

谢谢你。

回答by CMS

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;
}

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

编辑:由于您使用的是 jQuery 并且您想检查对象是否为“空”,因此 1.4 版本引入了$.isEmptyObject

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

回答by Aditya

This gives you the length of your associative array:

这为您提供了关联数组的长度:

Object.keys(testarray).length

回答by T.J. Crowder

There's no direct "length" or "size" call, you have to test the keys available within the object.

没有直接的“长度”或“大小”调用,您必须测试对象中可用的键。

Note that allJavaScript objects are associative arrays (maps), so your code would probably be better off using a generic object rather than an array:

请注意,所有JavaScript 对象都是关联数组(映射),因此您的代码最好使用通用对象而不是数组:

var testarray = {}; // <= only change is here
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

You can find out what the keys are in an object using for..in:

您可以使用以下命令找出对象中的键for..in

var name;
for (name in testarray) {
    // name will be 'one', then 'two', then 'three' (in no guaranteed order)
}

...with which you can build a function to test whether the object is empty.

...使用它您可以构建一个函数来测试对象是否为空。

function isEmpty(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
}

As CMS flagged up in his answer, that will walk through all of the keys, including keys on the object's prototype. If you only want keys on the object and not its prototype, use the built-in hasOwnPropertyfunction:

正如 CMS 在他的回答中所指出的那样,这将遍历所有键,包括对象原型上的键。如果您只想要对象上的键而不是它的原型,请使用内置hasOwnProperty函数:

function isEmpty(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}

回答by Aaron

I had this problem too, and I just realized the solution (and tested it in my browser):

我也有这个问题,我刚刚意识到解决方案(并在我的浏览器中进行了测试):

//given: ass_arr, an associative array
//result: count now holds the "length" of ass_arr 
var count = 0;
$.each(ass_arr, function(key, val) { count+=1; } );
alert(count); //number of iterable attributes in ass_arr

Let me know if this works for you! I'm writing it right into my code like this:

让我知道这是否适合您!我把它写进我的代码是这样的:

var devices = STATUS.devices,
  num_devices = 0;
$.each(devices, function(id, device) { num_devices+=1; } );
//num_devices set to number of devices

回答by Pointy

You don't really have an array there, so I'd avoid initializing it as such:

你那里并没有真正的数组,所以我会避免这样初始化它:

var testNotArray = { };
testNotArray['one'] = 'something';
// ...

Now this is inherently dangerous, but a first step might be:

现在这本质上是危险的,但第一步可能是:

function objectSize(o) {
  var c = 0;
  for (var k in o) 
    if (o.hasOwnProperty(k)) ++c;
  return c;
}

Again, there are a million weird ways that that approach could fail.

同样,这种方法可能会以一百万种奇怪的方式失败。

回答by ardsrk

You could calculate the length like below:

您可以计算如下长度:

var testarray = {}; // Use a generic object to store non-numeric indexes not an array
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';
var count = 0
for each(key in testarray)
 count = count + 1
alert(count); // count contains the number of items in the array

回答by Guffa

You can loop through the properties to count them:

您可以遍历属性来计算它们:

var cnt = 0;
for (i in testarray) cnt++;
alert(cnt);

Note that the for (... in ...)will also loop items added by a prototype, so you might want to count only the items added after that:

请注意,for (... in ...)也将循环由原型添加的项目,因此您可能只想计算之后添加的项目:

var cnt = 0;
for (i in testarray) if (testarray.hasOwnProperty(i)) cnt++;
alert(cnt);

If you just want to check if there are any properties, you can exit out of the loop after the first item:

如果只想检查是否有任何属性,可以在第一项之后退出循环:

var empty = true;
for (i in testarray) if (testarray.hasOwnProperty(i)) { empty = false; break; }
alert(empty);