Alfred
Alfred

Reputation: 21396

How to increment variable by 1 to limit, then rewind and repeat increment - jQuery

I have a variable holding a number, say 1. I want it to increment to 10. After reaching 10, it should then decrement to 1. Then again it should increment. I made a solution like;

var a = 1;
var i;
for(i=0;i<20;i++){
  //do something with var
  a++;
  if(a == 10){
    a = 1;
  }
}

Is there any simpler or better method for the same?

Upvotes: 2

Views: 4796

Answers (4)

plalx
plalx

Reputation: 43718

Using the modulo operator (%) is quite useful in these cases.

var x = 1;

//loop

//process

//increment
x = (x % 10) + 1; //1

Upvotes: 6

Nasser Torabzade
Nasser Torabzade

Reputation: 6710

for(i=0,a=1; i<20; i++,a++){
  //do something with var
  a==10 ? a=1 : null ;
}

Upvotes: 0

struthersneil
struthersneil

Reputation: 2750

If you want it to wrap back to 1 instead of 0, use the mod operator before the increment.

var a = 1;
for (i = 0; i < 20; ++i) 
{ 
  console.log(a); 
  a = (a % 10) + 1; 
}

Upvotes: 2

Siva Charan
Siva Charan

Reputation: 18064

for(i=0,a=1;i<20;i++,a++){
  //do something with var
  if(a==10){
    a = 1;
  }
}

Upvotes: 3

Related Questions