首页 > 解决方案 > 用 JavaScript 解释以下代码的输出,这似乎与预期不同

问题描述

下面的 JavaScript 代码应该给出32的输出,但答案是16。如何?

5 + 1 = 6;
6 + 5 = 11;
11 * 2 = 22;
22 + 10 = 32; (should have been answer as per me)

var x = 5;
x = (x++, alpha(x), x*2, x+10);
function alpha(x){
   return x+5;
}
console.log(x); 

标签: javascripthtmlecmascript-6

解决方案


alpha(x)函数是纯粹的,没有副作用,并且由于它不是逗号运算符的最后一个术语,因此它没有任何作用:您不妨将其完全删除。这部分也可以这样说x * 2。所以,你的代码相当于

var x = 5;
x = (x++, x+10);
console.log(x);

x++x一,因此x从 5 变为 6。然后x + 10计算为 16。

使用逗号运算符,整个表达式解析为右侧的值,在 final 之后,。另一种看待它的方式:

var x = 5;
x = (x++, alpha(x), x*2, x+10);
function alpha(x){
   return x+5;
}
console.log(x); 

相当于

var x = 5;

// comma operator translation starts here
x++; // Increments x; now x is 6
alpha(x); // Unused expression, doesn't do anything
x * 2; // Unused expression, doesn't do anything
x = x+10; // Adds 10 to x, assigns result to x; x is now 16
// comma operator translation ends here

function alpha(x){
   return x+5;
}
console.log(x);


推荐阅读