2011-08-16 16 views
5

c'è un modo per trovare il numero di bambini in un oggetto javascript diverso da un ciclo e utilizzando un contatore? Posso sfruttare jquery se sarà d'aiuto. Sto facendo questo:javascript come trovare il numero di bambini in un oggetto

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); 
} 
+1

in attesa di balzare sulle risposte jquery basato ... – jondavidjohn

+0

si stanno facendo un nuovo 'childScenesObj' ad ogni iterazione del loop, poi spingendolo su se stesso. Non penso che funzionerà. C'è bisogno di un altro 'var' lì –

+0

Posso usare jquery. – mheavers

risposta

25

le seguenti opere in ECMAScript5 (Javascript 1.85)

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

+1 per quello! Grande scoperta! – Brian

0

Se quell'oggetto è in realtà una matrice, .lunghezza otterrà sempre il numero di indici. Se ti riferisci a un oggetto e si desidera ottenere il numero di attributi/chiavi nell'oggetto, non c'è modo che conosco per che oltre un contatore:

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++; 
+0

È necessario filtrare le proprietà enumerabili dal prototipo in quel ciclo 'for ... in' utilizzando [' Object.hasOwnProperty'] (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/ oggetto/hasOwnProperty). –

+0

Puoi pubblicare un violino che dimostra la necessità? Non incorrere mai in un problema con l'enumerazione delle chiavi prima .... sarei molto ansioso di vederlo ... – Brian

+0

http://jsfiddle.net/mattball/YkXzU/ ricevo una sorpresa ora? –

Problemi correlati