PDA

Click to See Complete Forum and Search --> : nested loops question


tZ
08-11-2006, 03:10 PM
I have a question about javascript and hopefully someone can answer it.

In what order do nested loops execute?

Lets say I have a loop such as


var a = new Array(3)
for(var i=0; i<a.length; i++) {
a[i] = new Array(a.length);
for(var j=0; j<a.length; j++) {
a[i][j] = 'hello';
}
}


Since, the loops are nested how does the loop work.

Normally with one loop the thing would execute once and be done(once it loops through the length of the array. So if I nest a loop within it with a different variable as the loop argument does it:

execute the i loop entirly then move onto j?

exectute the i loop once then goes through the j loop 3 times. Then goes through the i loop and goes through the j loop three times. Then execute the i loop and go through the j loop 3 times?

Hopefully I explained that correctly.

So lets say for instance I wanted to fill the array that is created with the i loop like this- is it possible?


var a = new Array(3)
for(var i=0; i<a.length; i++) {
a[i] = new Array(a.length);
for(var j=0; j<a.length; j++) {
a[i][0] = 'hello';
}
}


or… is it not possible becase the other arrays havn't been created yet. So I can only fill it like this:


var a = new Array(3)
for(var i=0; i<a.length; i++) {
a[i] = new Array(a.length);
for(var j=0; j<a.length; j++) {
a[i][j] = 'hello';
}
}


Where 'a' will remain consistent for three times while 'j' changes?

if anyone could help that would be great. I'm going to try and run some test to figure it out but, its starting to confuss me,lol.

thanks

hypermorphism
08-11-2006, 03:20 PM
When nesting loops in any language, the inner loop is completed on each iteration of its containing loop. So if you have a loop that iterates 5 times inside a loop that iterates 4 times, the code inside the inner loop is executed 20 times in total.
In the case of the specific code you gave, you're going to fill every component of the 3x3 matrix with the string "hello".

tZ
08-11-2006, 03:29 PM
ok… so if I filled my a[2] array before it was created then nothing would happen as in this code.


var a = new Array(3)
for(var i=0; i<a.length; i++) {
a[i] = new Array(a.length);
for(var j=0; j<a.length; j++) {
a[i][0] = 'hello';
}
}


So the above code would only fill a[0][0] in the first loop?

hypermorphism
08-11-2006, 03:33 PM
Yep. Due to the inner loop it is in, it would set a[0][0] three times in the first iteration of the outer loop.

tZ
08-11-2006, 03:35 PM
cool

I thought that was how it worked but, wasn't sure.

thanks.