Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple counters in Javascript for loop

Before i tear my hair out and go down the wrong path in terms of debugging. Can someone confirm that this code will do as intended. Ie. animate 5 divs to different positions:

var i, j, k; $('#menuButton').click(function(){     for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){         $('.spinner #item' + i).animate({             left: '+=' + j,             bottom: '+=' + k           }, 500, function() {             // Animation complete.         });     } }); 

When i click the #menuButton, nothing happens and I get this error:

Uncaught SyntaxError: Unexpected token ; on the 'for()' line...

like image 205
benhowdle89 Avatar asked Dec 01 '11 21:12

benhowdle89


People also ask

Can I have two counters in a for loop?

You can create two counters that are updated simultaneously in a for loop using the comma operator. Multiple let and var declarations can also be joined with commas.

How do you make a loop with multiple variables?

And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.

Can you increment i in a for loop?

Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true). The for loop can proceed in a positive or negative fashion, and it can increment the loop control variable by any amount.


2 Answers

You've got some semicolons where you want commas:

for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30) { /* do work */ } 

You should only have three "statements" inside your for

for( [init]; [test]; [increments]) { [block] } 

To do multiple [inits] or [increments] you have to use the sometimes magical, but oft forgotten, comma operator

like image 56
J. Holmes Avatar answered Oct 03 '22 10:10

J. Holmes


too much semicolons there

for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){ 

should be

for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30){ 
like image 43
jAndy Avatar answered Oct 03 '22 12:10

jAndy