javascript - 用 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);
解决方案
该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);
推荐阅读
- javascript - 在反应路由器配置中编写异步组件以进行延迟加载
- javascript - 通过控制台在现有图表js上触发axispointer函数
- javascript - chrome上的音频有时会起作用,有时不起作用
- php - php“如果”没有答案
- php - 使用 EWS 使用 Oauth 2 阅读电子邮件时出现 UnauthorizedException
- c# - 如何从通过向下滚动刷新的动态网页中获取字符串
- php - 在 html 类属性中显示 php 代码
- java - How do we measure the total time taken to complete a flow across two different java applications?
- ipython - 氢将“-f”传递给 ArgumentParser
- c# - ASP.NET MVC C# - 使用 URL ACTION 传递动态参数