了解增量 [英] Understanding Incrementing
问题描述
例如:
var a = 123;
var b = a++;
现在 a
包含 124
和 b
包含 123
我知道b取的是a的值,然后a正在递增。但是,我不明白为什么会这样。为什么JavaScript的创建者会想要这个的主要原因。除了混淆新手之外,有什么好处?
I understand that b is taking the value of a and then a is being incremented. However, I don't understand why this is so. The principal reason for why the creators of JavaScript would want this. What is the advantage to this other than confusing newbies?
推荐答案
这就是为什么它被称为后递增运算符。基本上,一切都是表达式,它会产生一个值。 a + 1
是一个表达式,其结果为124.如果您使用<$ c $将此值分配给 b
c> b = a + 1 , b
的值为124.如果您没有将结果分配给任何内容, a + 1
仍然会产生值124,它会立即丢弃,因为你没有在任何地方捕捉它。
That's why it's called the "post-incrementing operator". Essentially, everything is an expression which results in a value. a + 1
is an expression which results in the value 124. If you assign this to b
with b = a + 1
, b
has the value of 124. If you do not assign the result to anything, a + 1
will still result in the value 124, it will just be thrown away immediately since you're not "catching" it anywhere.
BTW,偶数 b = a + 1
是一个返回124的表达式。赋值表达式的结果值是赋值。这就是为什么 c = b = a + 1
按预期工作的原因。
BTW, even b = a + 1
is an expression which returns 124. The resulting value of an assignment expression is the assigned value. That's why c = b = a + 1
works as you'd expect.
无论如何,关于这一点的特别之处带有 ++
和 -
的表达式除了返回值之外, ++
运算符直接修改变量。那么当你执行 b = a ++
时会发生什么,表达式 a ++
返回值123并递增 A
。 帖子 递增器首先返回值 然后 增量,而 pre incrementor ++ a
首先 增量,然后返回该值。如果您在没有作业的情况下单独编写 a ++
,您将不会注意到差异。通常使用 a ++
,作为的短手a = a + 1
。
Anyway, the special thing about an expression with ++
and --
is that in addition to returning a value, the ++
operator modifies the variable directly. So what happens when you do b = a++
is, the expression a++
returns the value 123 and increments a
. The post incrementor first returns the value, then increments, while the pre incrementor ++a
first increments, then returns the value. If you just wrote a++
by itself without assignment, you won't notice the difference. That's how a++
is usually used, as short-hand for a = a + 1
.
这是非常标准的。
这篇关于了解增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!