请解释一下这些“”以及——运营
为什么这段代码输出 3,而不是 2?
var i = 1;
i = ++i + --i;
console.log(i);
我预想:
++i // i == 2
--i // i == 1
i = 1 + 1 // i == 2
我哪里出错了?
Why this code outputs 3, not 2?
var i = 1;
i = ++i + --i;
console.log(i);
I expected:
++i // i == 2
--i // i == 1
i = 1 + 1 // i == 2
Where I made mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
更改按以下顺序发生:
i
(到 2)i
作为加法的左侧 (2)i
( 1)i
作为加法的右侧(1)i
(3)......看到你尝试这样做给了我一些关于为什么 JSLint 不喜欢的见解
++
和--
。The changes occur in this order:
i
(to 2)i
for the left hand side of the addition (2)i
(to 1)i
for the right hand side of the addition (1)i
(3)… and seeing you attempt to do this gives me some insight in to why JSLint doesn't like
++
and--
.这样看
x = (某物)
x = (++i) + (某物)
x = (2) + (某物)
x = (2) + (--i)
x = (2) + (1)
这些项从左到右计算,一旦第一个 ++i 被计算,当您使用 --i 更改其值时,它不会被重新计算。
Look at it this way
x = (something)
x = (++i) + (something)
x = (2) + (something)
x = (2) + (--i)
x = (2) + (1)
The terms are evaluated from left to right, once the first ++i is evaluated it won't be re-evaluated when you change its value with --i.
第二行是添加 2 + 1。
解释器将按顺序执行:
Your second line is adding 2 + 1.
In order, the interpreter would execute:
++i
等于 2,`--i' 等于 1。2 + 1 = 3。++i
equals 2, `--i' equals 1. 2 + 1 = 3.你的操作顺序有点偏差。过程如下:
存储在 i.
即 1. 2 + 1 = 3
You're a little off on your order of operations. Here's how it goes:
stored in i.
which is 1. 2 + 1 = 3
因为当您使用 ++i 时,i 的值会递增,然后返回。但是,如果使用 i++,则返回 i 的值,然后递增。 参考
Because when you use ++i the value of i is incremented and then returned. However, if you use i++, the value of i is returned and then incremented. Reference
因为您希望此代码像引用对象一样工作,并且在一元运算完成之前不会收集值。但在大多数语言中,首先计算表达式,因此 i 返回 i 的值,而不是 i 本身。
如果你有 ++(--i) 那么你就是对的。
简而言之,不要这样做。
该操作的结果在每种语言/编译器/解释器中的定义并不相同。因此,虽然它在 JavaScript 中导致
3
,但在其他地方可能会导致2
。Because you're expecting this code to work as if this is a reference object and the values aren't collected until the unary operations are complete. But in most languages an expression is evaluated first, so i returns the value of i, not i itself.
If you had ++(--i) then you'd be right.
In short, don't do this.
The result of that operation isn't defined the same in every language/compiler/interpreter. So while it results in
3
in JavaScript, it may result in2
elsewhere.