Javascript 使用 Jquery 计算对象字面量中的对象数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13802987/
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
To count the number of objects in object literal using Jquery
提问by User1674987
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.
我想在这个对象文字中使用 Jquery 计算对象的数量。
回答by Ian
You could use Object.keys(animals).length
你可以用 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:
或者可能是最有效的,也可能不是最有效的 jQuery 解决方案之一:
var count = $.map(animals, function(n, i) { return i; }).length;
回答by Denys Séguret
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).
如果你想要一些跨浏览器的东西,也可以在 IE8 上运行,你不能以一种非常干净的方式做到这一点(请参阅keys 属性的兼容性)。
I suggest this :
我建议:
var n = 0;
for (var _ in animals) n++;
(as it is an object literal, no need for hasOwnProperty)
(因为它是一个对象字面量,不需要 hasOwnProperty)
回答by neiker
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() );

