Dim
Dim

Reputation: 4807

JQuery from $.each to for loop

I am very new to JQuery, from examples I have managed to create loop, I know it`s simple question but I need your help. How can I convert $.each loop:

$.getJSON('db.json', function(data) 
 {
   $.each(data, function(key, val) 
    {

        if(typeof val === 'object') 
        {
            checkObj(key, val, items);
        } 

    });
}

to for loop? I have tried:

for (var i=0; i< data.length; i++)
    {

        if(typeof val === 'object') 
        {
            checkObj(key, val, items);
        } 

    }

but what to do with key and val?

Upvotes: 2

Views: 99

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

You're very close (for arrays). Just add:

var val;

at the top and then

val = data[i];

in the loop.

var i, val;
for (i=0; i< data.length; i++)
{
    val = data[i];
    if(typeof val === 'object') 
    {
        checkObj(i, val, items);
        //       ^----- `i`, not `key`, since you used `i` instead of `key` for the loop
    } 

}

But my question would be: Why do that? $.each is very handy, not least because it provides this nice contained scope for the key/i and val variables. If you're worried about making a function call on each iteration, don't be.

$.each also has a dual-nature: When you're giving it an array, it loops through the array elements. But when you give it an object, it loops through the enumerable properties of the object. Both are quite handy.

Upvotes: 7

Related Questions