Javascript增量评估的操作顺序 [英] Javascript increment operation order of evaluation
问题描述
我知道后缀/前缀增量/减量运算符的作用。在javascript中,这似乎没有什么不同。
I know the what the postfix/prefix increment/decrement operators do. And in javascript, this seems to be no different.
虽然我可以轻松猜出这一行的结果:
While I can guess the outcome of this line easily:
var foo = 10; console.log(foo, ++foo, foo, foo++, foo);
// output: 10 11 11 11 12
as + +
运算符出现在单独的表达式中。
as ++
operators appear within separate expressions.
由于这些运算符出现在同一个表达式中,因此有点复杂:
It gets a bit complicated as these operators appears within the same expression:
var foo = 10; console.log(foo, ++foo + foo++, foo);
// output[1]: 10 22 12
// Nothing unexpected assuming LTR evaluation
var foo = 10; console.log(foo, foo++ + ++foo, foo);
// output[2]: 10 22 12
// What? Ordering is now different but we have the same output.
// Maybe value of foo is evaluated lazily...
var foo = 10; console.log(foo, foo + ++foo, foo);
// output[3]: 10 21 11
// What?! So first 'foo' is evaluated before the increment?
我的问题是,Javascript(在这种情况下是V8,因为我在Chrome中测试了这些)最后以不同的方式评估第二和第三个例子中的加法表达式?
and my question is, how does Javascript (V8 in this case, as I tested these in Chrome) end up evaluating the addition expression in 2nd and 3rd example differently?
为什么 foo
最终评估的结果与 foo ++不同
。是不是postfix ++
应该在表达式后递增,只是在表达式中求值为 foo
?
Why does foo
end up evaluating differently than foo++
. Isn't postfix ++
supposed to increment after the expression and just evaluate to foo
within expression?
推荐答案
看看:
foo++ + ++foo
将其重写为:
foo++ →
addition_lhs = foo // addition_lhs == 10
foo += 1 // foo == 11
++foo →
foo += 1 // foo == 12
addition_rhs = foo // addition_rhs == 12
addition_lhs + addition_rhs == 10 + 12 == 22
和 foo + ++ foo
:
foo →
addition_lhs = foo // addition_lhs == 10
++foo →
foo += 1 // foo == 11
addition_rhs = foo // addition_rhs == 11
addition_lhs + addition_rhs == 10 + 11 == 21
所以从左到右评估所有内容,包括增量
So everything is evaluated left to right, including the incrementation.
要理解的关键规则是在JavaScript中执行整个左侧(LHS),并记住值,之后任何操作都在右侧完成(RHS)。
The crucial rule to understand is that in JavaScript the whole left hand side (LHS) is executed, and the value memorized, before any operation gets done on the right hand side (RHS).
您可以通过读取标准或只是在表达式中放置一个运行时错误,看看会发生什么:
You can either confirm the evaluation order by reading the standard or just place a runtime error in your expression and look what happens:
alert(1) + alert(2) + (function () { throw Error(); })() + alert(3)
这篇关于Javascript增量评估的操作顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!