Using for..in to loop through an object

I'm trying to use for..in loop to select the objects within a variable and it doesn't show up the necessary Li objects.

var mUlLi = $(mUl).find('>li');      //select all li's in main Ul   
var listLength = $(mUlLi).length;
if(listLength >0 ){
    /*for(i=0;i <listLength; i++) {
        console.log(mUlLi[i]);   // works fine show the li objects  
    }*/
    for(var obj in mUlLi) {
        console.log(obj);   // show's diff objects
    }
}

How can i fix this ?

Answers


jQuery has an each() that does the same thing.

$(mUl).find('>li').each(function(){ //for each of the elements found
    console.log(this);              //in here, "this" is the DOM element <li>
});

If you used a for in on a jQuery object, you'd also be looping through the jQuery methods and properties.

However, if you really want to do a for loop on the elements you got from that jQuery (because you didn't want to use each()), then do it directly:

var nodes = $(mUl).find('>li'),
    nodesLength = nodes.length,
    i, node;

for(i=0,i<nodesLength;i++){
    node = nodes[i];
}

mUlLi (problematic variable name) is not a regular object, is a jQuery collection. You can iterate with each().

mUlLi.each(function(){
   // `$(this)` is the current jQuery element
})

How about using jQuery's each function?

http://api.jquery.com/jQuery.each/

$(mUl).find('>li').each(function(i,v) {
    console.log(v);
});

You can fix this by using the proper way to iterate over an array - for(.. in ..) is NOT meant for iterating over array elements/indexes but for object properties - which is not what you want here.

Simply use the jQuery way via .each():

mUlLi.each(function() {
    console.log(this);
});

If you do not want this for some reason (probably not a valid reason!), you could also use a good old for loop:

for(var i = 0; i < listLength; i++) {
    var elem = mUlLi[i];
    console.log(elem);
}

Need Your Help

'NSInternalInconsistencyException', reason: 'Only run on the main thread!' error

ios iphone objective-c multithreading cocoa-touch

So I know the reason for this error, but I'm not really sure how to get around it.

python mysql database connection error

python mysql database-connection mysql-python remote-server

I am trying to access the remote database from one Linux server to another which is connected via LAN.