问题描述
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++
,然后递增。
如果x
是10
,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
(这使我们{{1 }})。 (Useful link - look at chapter Modify-in-place)
10
说: ++x
将被重新初始化(重新分配)为之前的内容(x
)加上10
。另外,返回1
的新值(x
)。 (In same link,look at the below chapter Increment/Decrement)
如果相反,我们有11
会说:'将1加到x,但不返回此新值-在进行此加法之前返回该值(x++
):
10