鍍金池/ 問答/HTML/ 關于運算符跟表達式副作用

關于運算符跟表達式副作用

    var a = 1, c;
    
    c = (a++) + a;
    console.log(c); // 3
問題來了,先執(zhí)行a++,那a不就等于2了么

最后應該是 c = (2) + 2,結果應該是4才對啊,為什么最后會是3

++不是有個隱式賦值么,為什么這里的a不會受到副作用影響?
回答
編輯回答
情未了

a++是先返回值在進行本身運算的
++a是先進行本身運算在返回值的

所以這個表達式(a++) + a; 運算邏輯為: 先返回(a++)的值為 a等于 1,然后在進行 ++運算這時a=2所以c=3;

如果你的表達式為(++a) + a;那么結果就為4

2017年5月31日 21:14
編輯回答
絯孑氣

c = (a++) + a is equivalent to the following:

var t1 = a;
a++;
var t2 = a;
c = t1 + t2;

In which t1 is 1 and t2 is 2, which is leading to the result 3.

And if you write the code like c = (++a) + a, it will be interpreted as the following:

a++; // or more precisely, ++a
var t1 = a;
var t2 = a;
c = t1 + t2;

And you will get 4;

2017年10月30日 01:14