Welcome to WebmasterWorld Guest from 54.161.178.52

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)

#### Junior Member

joined:June 26, 2004
posts:155

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)

#### New User

joined:Feb 6, 2006
posts:23

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)

#### Preferred Member

joined:Sept 4, 2002
posts:508

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.} }``