Incrementing a variable in a cycle (modulo)

2019-08-03 07:27发布

问题:

I wish to cycle the values of a variable (call it x) through the pattern 0, 1, 2, 0, 1, 2, … upon activation of a function (call it update). I've managed to get 1, 2, 0, 1, 2, 0, … by doing:

var x = 0;

function update() {
  x = ++x % 3;
}

Then I tried the post-increment operator instead, and the value of x just remains at 0:

var x = 0;

function update() {
  x = x++ % 3;
}

Then the more I thought about this code, the more confused I got. I think 0 modulo 3 is being done first, then the assignment (of 0) to x, but then is x not incremented to 1? (it seems that it isn't, but that's not what I want anyway — I want the pattern to start at 0. Can someone explain what's going on with this code and how to achieve the pattern starting at 0?

回答1:

Your second example of code is doing this

  1. Store the old value of x
  2. Increment x
  3. Modulo the old value of x by 3
  4. Store the result of the modulus in x

Your first code should give you the correct solution if you call it like this:

look_at_value()
update()
look_at_value()
update()
...

If you want to call update before looking at the value, you will need to initialize x = -1 (or 2 mod 3)

Clearer code would be:

function update() {
    x = (x+1) % 3;
}