Thursday 16 October 2014

JavaScript Loop Wrapping (0,1,2...6 and repeat from 0)

Sometimes you want your for loop to iterate over a given set of numbers and, when it reaches the end of the series, wrap around to the first value. For example, something as simple as ,,
0,1,2,3,4,5,6....0,1,2,3,4,5,6....etc


  To do this, you can implement the following for loop

  for(var counter=0, iterations=0; 
    iterations < 20;               
    counter=( counter == 6? 0 : counter+1 ), iterations++ ){ 
        console.log(counter);
}

  //outputs 0,1,2,3,4,5,6,0,1,2,3,4,5,6.....


  Or,

  for(var counter=0, modulus = 0;       
    iterations < 20;                 
    counter++, modulus=counter%6 ){   
        console.log(modulus);
}

  //outputs 0,1,2,3,4,5,6,0,1,2,3,4,5,6.....

No comments:

Post a Comment