Multiple counters in Javascript for loop

27,236

Solution 1

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

Solution 2

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){

Solution 3

You made gramatical errors in your code that you could have easily spotted had you used static code analysis tools such as the lovely JSHint.

In addition, you should further understand the use of the comma operator in JavaScript, our site has a few answers on it already.

Share:
27,236
benhowdle89
Author by

benhowdle89

Consultant software engineer and advisor to companies building software products.

Updated on June 19, 2020

Comments

  • benhowdle89
    benhowdle89 almost 4 years

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