views:

67

answers:

4

Can you have two counts with for loop?

Example:

for( var count1 = 0, count2 = 0; count1 < 5; count1++, count2++ ) { }

If not, what would be a good way to handle two separate counts other than using two loops?

+1  A: 

Yes, that's valid.

T.J. Crowder
A: 

I don't think you can have multiple counter variables in a for loop. Do you intend the counter variables (count1 and count2) to increment at the same time after each iteration? If so, this is what I'd do:

var count2 = 0;
for (var count1 = 0; count1 < 5; count1++)
{
  // Do stuff
  count2++;
}

Edit: Nevermind. It's legal. My Javascript's rusty and I've never used multiple control variables in a for loop.

Andrew
+1  A: 

Your loop syntax is completely valid. No problem at all. :)

Jacob Relkin
+1  A: 

Yes, of course you can have multiple initializations in a for loop.

Alex