CansomeoneexplainthiscodeinJavaScriptwith++andbrackets?
var m=10;
n=(m++)+(++m)+(m++)+(++m);
Output is
n=48 m=14
How does this answer occur?
回答
Initially m=10. Now when ++ is executed, it will add 1 to the variable. In your code, there are 4 occurences of either ++m or m++, so it will be 14 at the end.
When ++ appears before the variable like ++m, it will add 1 first and use the variable in code. But when it appears after the variable like m++, the variable will be used first and then add 1.
所以在n=(m++)+(++m)+(m++)+(++m);,
m++-m 将在代码中用作 10 并变为 11。
++m-m将首先增加 1,因此 11+1 =12 并将在代码中使用。
m++- m 将在代码中用作 12 并变为 13。
++m-m将首先增加 1,因此 13+1 = 14 并将在代码中使用。
因此,最终结果将如下所示:
n=10+12+12+14
var m = 10;
var m1 = m++;
var m2 = ++m;
var m3 = m++;
var m4 = ++m;
var n = m1 + m2 + m3 + m4;
console.log('n: ' + n);
console.log('m: ' + m);
console.log('(m++): ' + m1 + ', (++m): ' + m2 + ', (m++): ' + m3 + ', (++m): ' + m4);
console.log('---');
var x = 10;
var y = (x++) + (++x) + (x++) + (++x);
console.log('y: ' + y);
console.log('x: ' + x);
THE END
二维码