Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run two for loops in one statement in javascript?

Can I run two for loops in one statement in javascript? Would I do it like this?

for(initialize1,initialize2; condition1,condition2; incrementation1,incrementation2) 
like image 978
samdonly1 Avatar asked Feb 18 '23 21:02

samdonly1


1 Answers

Yes you can do a for loop like that, but you have one and just one condition for check. If you can make it check just a one condition for all of your variables for example an And (&&) conditional expression this will work fine, or if you just use the other variables for do something else it will work fine too.

Try it:

for(var i=j=k=0; j<9 && k<12;i++, j++, k++){
    console.log(i,j,k);      
    i = 12;
}

@samdonly1

Always you will have just one evaluation, but you can do something like this:

function evalFor(i, j, k){
   if (k == 9) return false;
   else if (j == 7) return false;
   else if (i == 12 && j == 6) return false;
   else return true;
}
for(var i=j=k=0; evalFor(i, j, k);i++, j++, k++){
    console.log(i,j,k);     
    i = 11;
}

In this case you can check your variables i, j, k in other function and decide if the loop stops or goes on.

like image 198
Inm0r74L Avatar answered Feb 27 '23 10:02

Inm0r74L