Javascript:为什么前缀运算符使用模数而不是后缀运算符?(Javascript: Why does prefix operator work with modulus but not post

编程入门 行业动态 更新时间:2024-10-08 00:32:30
Javascript:为什么前缀运算符使用模数而不是后缀运算符?(Javascript: Why does prefix operator work with modulus but not postfix operator?)

我试图使一个函数递增,直到它达到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, 0

And

function newRun () { console.log(j); j = ++j % 3; } // Called three times it logs 0, 1, 2

Why 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;

更多推荐

本文发布于:2023-07-30 15:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338800.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   前缀   后缀   而不是   模数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!