homepage Welcome to WebmasterWorld Guest from 54.204.127.191
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Nested for loops
Is a variable number of them possible?
directrix




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

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




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

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




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

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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved