使用Jquery计算对象文字中的对象数 [英] To count the number of objects in object literal using Jquery
本文介绍了使用Jquery计算对象文字中的对象数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
var animals = {
"elephant": {
"name" : "Bingo",
"age" : "4"
},
"Lion": {
"name" : "Tango",
"age" : "8"
},
"Tiger": {
"name" : "Zango",
"age" : "7"
}
}
我想在此对象文字中计算使用Jquery的对象数。
I want to count the number of objects using Jquery in this object literal.
推荐答案
您可以使用 Object.keys(animals).length
或
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
或者许多jQuery解决方案中的一种,可能是也可能不是最有效的:
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;
这篇关于使用Jquery计算对象文字中的对象数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文