HI,
我正在使用JSON解析的返回对象集。
{
"word":[
"offered",
"postings"
],
"annotation":[
["offered highlighted","this is also given as annotation","This annotation has been added here currently","offering new annotation points","\"offered\" is in the sense of languages"],
["my postings","this is new annotation for postings.","my postings","this is posting annotation.... Working for the feature of the annotation."]
],
"user":[
["","","vinoth","Anonymous","Vinoth"],
["Anonymous","vinoth","Anonymous","Arputharaj"]
],
"id":[
["58","60","61","63","68"],
["32","57","59","62"]
],
"comment":
{
"id58":["first comment","This is a old comment for this annotation","Next level of commenting.","Fourth comment to this annotation","testing"],
"id61":["this is an old annotation.\r\nMy comment is very bad about this.","Second comment to this annotation"],
"id57":["I want to add one more comment to this"]
},
"commentUser":{
"id58":["vinoth","Anonymous","Vinothkumar","Vinothkumar","vinoth"],
"id61":["Anonymous","Commentor"],
"id57":["vinoth"]
}
}
我想知道每个对象和数组的长度。
我使用.length
来获取annotation[0].length
的长度。我得到了预期的结果,即:5。同样是“用户”& “ID”。
但是我没有得到“字”,“id58”,“id61”等的长度......
另外,我想知道comment
&的长度。 commentUser
。
请帮助我。
答案 0 :(得分:7)
要计算对象具有的属性数,您需要遍历属性,但记得使用hasOwnProperty
函数:
var count = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
count++;
}
}
如果您忘记这样做,您将循环继承属性。如果你(或某些库)已经为Object
的原型分配了一个函数,那么所有对象似乎都具有该属性,因此看起来一个项目比它们本质上“更长”。
为避免记住这一点,请考虑使用jQuery的each
代替:
var count = 0;
$.each(obj, function(k, v) { count++; });
更新使用当前浏览器:
Object.keys(someObj).length
答案 1 :(得分:5)
示例中的密钥word
的值(我们称之为obj
)是一个数组,因此obj.word.length
应为2.
comment
和commentUser
的值是一个对象,它本身没有长度,因此您需要自己计算:
var length=0;
for(var dummy in obj.comment) length++;