++ operator returns original value if placed after operand — how?

﹥>﹥吖頭↗ 提交于 2019-12-12 04:33:47

问题


As far as I've been led to understand, x++ is essentially a terser way of saying x = x + 1. So far, so clear. In front-end Javascript, I've occasionally seen ++x — I seem to remember from a jsPerf test I can no longer find (how does one Google ++ effectively?) that this somehow had a small performance benefit in a particular version of IE, and let it go at that.

However I've recently encountered something that speaks of a weird quirk in execution order (JS code):

var x = 1;
console.log(x++); // 1 (?!)
console.log(x);   // 2

…whereas

var x = 1;
console.log(++x); // 2 (what I would've expected)
console.log(x);   // 2

I can't get my head around this. How can we return the unmodified variable when the operation and assignment are within the parenthesis, and thus by all rights should be executed before console.log is even invoked, let alone executed and returned?


回答1:


Those are two different things

x++

is a post-increment. It returns x before the change but then changes it:

tmp = x;
x = x+1;
return tmp;

whereas

++x

is a pre-increment. It first changes x and returns the new value afterwards:

x = x+1;
return x;

The second one is also slightly faster as your compliler/interpreter doesn't need to create a temporary variable and copy the data across.




回答2:


x++ gets the value, then increments it.

++x increments the value, then gets it.

This is the behavior in every language I've used that supports these operators.




回答3:


Using ++ AFTER the variable increments the value after that line of code.

Likewise, using ++ BEFORE the variable increments the value before using it in that line of code.

Cool huh?

var x = 1;
x++;
console.log(x++); // 2 (?!)
console.log(x);   // 3
console.log(++x); // 4
console.log(x++); // 4
console.log(x);   // 5



回答4:


You're talking about the difference between the pre- and post- increment operators. In the pre- case, the operation is essentially (x = x + 1; yield x), and in the second case it's (yield x; x = x + 1).



来源:https://stackoverflow.com/questions/13864091/operator-returns-original-value-if-placed-after-operand-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!