javascript如何查找对象中的子项数

时间:2011-08-16 15:57:59

标签: javascript object

有没有办法找到javascript对象中的子项数,而不是运行循环和使用计数器?我可以利用jquery,如果它会有所帮助。我这样做:

var childScenesObj = [];
var childScenesLen = scenes[sceneID].length; //need to find number of children of scenes[sceneID]. This obviously does not work, as it an object, not an array.


for (childIndex in scenes[sceneID].children) {
    childSceneObj = new Object();
    childSceneID = scenes[sceneID].children[childIndex];
    childSceneNode = scenes[childSceneID];
    childSceneObj.name = childSceneNode.name;
    childSceneObj.id = childSceneID;
    childScenesObj  .push(childSceneObj);
}

2 个答案:

答案 0 :(得分:31)

以下适用于ECMAScript5(Javascript 1.85)

var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2

答案 1 :(得分:0)

如果该对象实际上是一个数组,。length将始终为您提供索引数。如果你指的是一个对象,并且你想获得对象中的属性/键的数量,除了计数器之外我无法知道其他内容:

var myArr = [];
alert(myArr.length);// 0
myArr.push('hi');
alert(myArr.length);// 1

var myObj = {};
myObj["color1"] = "red";
myObj["color2"] = "blue";

// only way I know of to get "myObj.length"
var myObjLen = 0;
for(var key in myObj)
  myObjLen++;