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?