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
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