To count the number of objects in object literal using Jquery

一世执手 提交于 2019-12-20 14:17:52

问题


Code:

var animals = {
                    "elephant": {
                                    "name" : "Bingo",
                                    "age" : "4"
                                },
                    "Lion":     {
                                    "name" : "Tango",
                                    "age" : "8"
                                },
                    "Tiger":    {
                                    "name" : "Zango",
                                    "age" : "7"
                                }
                }

I want to count the number of objects using Jquery in this object literal.


回答1:


You could use Object.keys(animals).length

Or

var count = 0;
for (var animal in animals) {
    if (animals.hasOwnProperty(animal)) {
        count++;
    }
}
// `count` now holds the number of object literals in the `animals` variable

Or one of many jQuery solutions that may or may not be the most efficient:

var count = $.map(animals, function(n, i) { return i; }).length;



回答2:


If you want something cross browser, that is also working on IE8, you can't do it in a really clean way (see compatibility of the keys property).

I suggest this :

var n = 0;
for (var _ in animals) n++;

(as it is an object literal, no need for hasOwnProperty)




回答3:


Can't you use an array?

Anyway, in an object, you can do that:

Object.prototype.length = function() {
    var count = 0, k=null;
    for (k in this) {
        if (this.hasOwnProperty(k)) count++;
    }
    return count;
}
console.log( animals.length() );


来源:https://stackoverflow.com/questions/13802987/to-count-the-number-of-objects-in-object-literal-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!