得到 Json 对象上的项目总数?

可能的复制品:
Javascript 对象的长度(即关联数组)

我有个类似的东西:

var jsonArray = {
'-1': {
'-1': 'b',
'2': 'a',
'10': 'c'
},
'2': {
'-1': 'a',
'2': 'b',
'10': 'a'
},
'5': {
'-1': 'a',
'2': 'a',
'10': 'b'
}
};

我试图得到它的长度,问题是 jsonArray.length返回的是5,而不是3(这是它的总项目)。该数组相对较长(有1000x2000个项目) ,这必须每秒执行很多次。我怎样才能更有效地获得项目的数量?

217202 次浏览

Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length returns undefined rather than 5.

This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object