JavaScript中的x ++有什么作用?

Yun*_* Li 1 javascript

我有一个非常简短的问题,但它让我很困惑.

var y = 3, x = y++;
Run Code Online (Sandbox Code Playgroud)

x的价值是多少?

我认为答案应该是4,但实际上它是3.

任何人都可以解释我的原因吗?

Bar*_*mar 5

y++被称为后递增 - 它将原始值作为表达式的值返回之后递增变量.所以

x = y++;
Run Code Online (Sandbox Code Playgroud)

相当于:

temp = y;
y = y + 1;
x = temp;
Run Code Online (Sandbox Code Playgroud)

如果要返回新值,则应使用++y.这称为预增量,因为它返回变量之前递增变量.该声明

x = ++y;
Run Code Online (Sandbox Code Playgroud)

相当于:

y = y + 1;
x = y;
Run Code Online (Sandbox Code Playgroud)