我不明白为什么变量 y 等于 4?

I'm not understanding why the variable y is equal to 4?

我有点理解为什么 y 等于 4 的评论中的推理,但我不明白为什么用 [=14 声明变量 y =] 它不会增加它并分配 3 而不是只采用先前声明的值?

// In this line: var y = x++ the value of x is assigned to y before x is incremented, 
// so y equals 3 on line 2, while x equals 4. 
// Therefore on line 3, y now equals 4 instead of 5.

var x = 3;
var y = x++;
y += 1;

这与您放置 ++ 的位置有关。 ++ 的工作方式(这只是它的语法)是,如果你在 x 之后使用它,代码将增加 y 变量,但是表达式然后 returns 在它增加 x 之前的值(所以它会只是 return x 的值)。你想要的是首先发生增量。所以下面的代码应该可以增加值,因为它会首先增加,然后 return 变量。

let x = 3;
let y = ++x;
y += 1;

console.log(y); // Returns 5