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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7081165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:54:16  来源:igfitidea点击:

javascript how to find number of children in an object

javascriptobject

提问by mheavers

is there a way to find the number of children in a javascript object other than running a loop and using a counter? I can leverage jquery if it will help. I am doing this:

除了运行循环和使用计数器之外,有没有办法在 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);
}

回答by Eliu

The following works in ECMAScript5 (Javascript 1.85)

以下在 ECMAScript5 (Javascript 1.85) 中有效

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

回答by Brian

If that object is actually an Array, .length will always get you the number of indexes. If you're referring to an object and you want to get the number of attributes/keys in the object, there's no way I know to that other than a counter:

如果该对象实际上是一个数组,则 .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++;