var a = 1, c; c = (a++) + a; console.log(c); // 3问题来了,先执行a++,那a不就等于2了么最后应该是 c = (2) + 2,结果应该是4才对啊,为什么最后会是3++不是有个隐式赋值么,为什么这里的a不会受到副作用影响?
2 回答
慕容森
TA贡献1853条经验 获得超18个赞
a++是先返回值在进行本身运算的++a是先进行本身运算在返回值的
所以这个表达式(a++) + a; 运算逻辑为: 先返回(a++)的值为 a等于 1,然后在进行 ++运算这时a=2所以c=3;
如果你的表达式为(++a) + a;那么结果就为4了
慕斯709654
TA贡献1840条经验 获得超5个赞
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;
添加回答
举报
0/150
提交
取消
