2

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?

4

4 回答 4

5

在这些情况下,使用模运算符 ( %) 非常有用。

var x = 1;

//loop

//process

//increment
x = (x % 10) + 1; //1
于 2013-10-20T18:45:40.753 回答
3
for(i=0,a=1;i<20;i++,a++){
  //do something with var
  if(a==10){
    a = 1;
  }
}
于 2013-10-20T18:46:40.843 回答
2

如果您希望它返回 1 而不是 0,请在增量之前使用 mod 运算符。

var a = 1;
for (i = 0; i < 20; ++i) 
{ 
  console.log(a); 
  a = (a % 10) + 1; 
}
于 2013-10-20T18:52:39.627 回答
0
for(i=0,a=1; i<20; i++,a++){
  //do something with var
  a==10 ? a=1 : null ;
}
于 2013-10-20T19:12:35.363 回答