Welcome to WebmasterWorld Guest from 54.227.83.19

Forum Moderators: open

Message Too Old, No Replies

Nested for loops

Is a variable number of them possible?

     

directrix

4:30 pm on Aug 13, 2006 (gmt 0)

10+ Year Member



Is it possible, maybe using eval in some clever way, to code a variable number of nested for loops? Below is an example of five nested for loops. I'd like to be able, simply by extending the array i to more elements, to dynamically generate the for loop code.

var i = [0, 0, 0, 0, 0], lim = 2;
for (i[0] = 0; i[0] < lim; i[0]++)
for (i[1] = 0; i[1] < lim; i[1]++)
for (i[2] = 0; i[2] < lim; i[2]++)
for (i[3] = 0; i[3] < lim; i[3]++)
for (i[4] = 0; i[4] < lim; i[4]++) {
// Some code.
}

supermoi

11:42 pm on Aug 13, 2006 (gmt 0)

5+ Year Member



You could do that using recursivity.

For example:

var nbLoops = 5;

test(1);

function test(count) {
for(...) {...} // Your code for the loop goes there
if(count < nbLoops) test(count+1);
else return;
}

garann

7:55 pm on Aug 17, 2006 (gmt 0)

10+ Year Member



Not this?


var i = [0, 0, 0, 0, 0], lim = 2;
for (var j=0;j<i.length;j++) {
for (i[j] = 0; i[j] < lim; i[j]++) {
// Some code.
}
}
 

Featured Threads

Hot Threads This Week

Hot Threads This Month