使用Jquery计算对象文字中的对象数

码:

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

我想在此对象文字中使用Jquery计算对象的数量。

你可以使用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解决方案中的一个可能是也可能不是最有效的:

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

如果你想要一些跨浏览器的东西,那也是在IE8上工作,你就不能以一种非常干净的方式去做(参见keys属性的兼容性 )。

我建议这个:

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

(因为它是一个对象文字,不需要hasOwnProperty)

你不能使用数组吗?

无论如何,在一个对象中,你可以这样做:

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