javascript x++ 和 ++x 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4186027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:37:49  来源:igfitidea点击:

What is the difference between x++ and ++x

javascriptc++

提问by steve

Possible Duplicate:
Incrementing in C++ - When to use x++ or ++x?

可能的重复:
在 C++ 中递增 - 何时使用 x++ 或 ++x?

What is the difference between x++ and ++x ?

x++ 和 ++x 有什么区别?

回答by Justin Niessner

x++executes the statement and then increments the value.

x++执行语句,然后增加值。

++xincrements the value and then executes the statement.

++x增加值,然后执行语句。

var x = 1;
var y = x++; // y = 1, x = 2
var z = ++x; // z = 3, x = 3

回答by Ben Lee

++xis higher in the order of operations than x++. ++xhappens prior to assignments, but x++happens after assignments.

++x操作顺序高于x++++x发生在赋值之前,但x++发生在赋值之后。

For exmaple:

例如:

var x = 5;
var a = x++;
// now a == 5, x == 6

And:

和:

var x = 5;
var a = ++x;
// now a == 6, x == 6

回答by Rocket Hazmat

x++returns x, then increments it.

x++返回 x,然后增加它。

++xincrements x, then returns it.

++x增加 x,然后返回它。

回答by SLaks

If you write y = ++x, the yvariable will be assigned after incrementing x.
If you write y = x++, the yvariable will be assigned beforeincrementing x.

如果你写y = ++xy变量将在递增后分配x
如果你写y = x++y变量将递增之前被赋值x

If xis 1, the first one will set yto 2; the second will set yto 1.

如果x1,第一个将设置y2;第二个将设置y1