我试图使一个函数递增,直到它达到3然后从零开始(因此,调用三次它将记录0然后1然后2当使用%运算符与前后修复操作符时,我有困惑结果。
这是我的两个功能:
var i, j = 0, 0 function run () { console.log(i); i = i++ % 3; } // Called three times logs 0, 0, 0和
function newRun () { console.log(j); j = ++j % 3; } // Called three times it logs 0, 1, 2为什么前缀运算符工作而后缀不工作(即在第一个函数中为什么i从不递增?
I am trying to make a function that increments until it reaches 3 and then starts back from zero (so, called three times it would log 0 then 1 then 2. When using the % operator with the pre and post fix operators, I have confusing results.
Here are my two functions:
var i, j = 0, 0 function run () { console.log(i); i = i++ % 3; } // Called three times logs 0, 0, 0And
function newRun () { console.log(j); j = ++j % 3; } // Called three times it logs 0, 1, 2Why does the prefix operator work and the postfix does not (i.e. in the first function why is i never incremented?
最满意答案
这与模运算符没有任何关系。 甚至
i = i++;不起作用 - 它取一个值,递增它,然后用最初获取的值覆盖它。 另请参阅循环中i ++和++ i的区别? 他们如何工作。
你可能想写
i = (i + 1) % 3;This doesn't have anything to do with the modulo operator. Even
i = i++;doesn't work - it takes a value, increments it, and then overwrites it with the initially taken value. See also Difference between i++ and ++i in a loop? for how they work.
You probably want to write
i = (i + 1) % 3;更多推荐
发布评论