你如何计算这个

How do you calculate this

var x = 5;
x *= 2;
console.log(++x);

11的答案如何?我很困惑

var x = 5; // x = 5
x *= 2; // multiply x with 2 (x = 10)
console.log(++x); // console.log x plus 1 (11)

使用此语法的更常见方式是使用加号或减号:

x += 1;
// is a shorthand for
x = x + 1;

x *= 2;
// is a shorthand for
x = x * 2;

// etc.

++x先递增,然后用THEN,vs:
x++ 首先使用,然后递增。

如果 x10,
console.log(++x) 将导致“11”,与:
console.log(x++) 将得到“10”。

在这两种情况下,在代码行之后,x 将是 11

var x = 5;
x *= 2;
console.log(x);
console.log(++x);

x *= 2; 说:x 将被重新初始化(重新分配)到之前的值(5)乘以 2(这给出我们 10)。 (Useful link - look at chapter Modify-in-place)

++x 说:x 将被重新初始化(重新分配)到之前的状态(10)加上 1。此外,return xs 新值 (11)。 (In same link, look at the below chapter Increment/Decrement)

相反,如果我们有 x++,它会说:'将 1 添加到 x 但不 return 这个新值 - return添加之前的值 (10):

var x = 5;
x *= 2;
console.log(x++);