What is quot;x amp;amp; foo()quot;?(什么是“xamp;amp;foo()?)
问题描述
我在其他地方看到 某处,
x &&foo();
等于
if(x){
foo();
}
我对其进行了测试,他们确实做了同样的事情.
但为什么?x && 到底是什么?foo()
?
I tested it and they really did the same thing.
But why? What exactly is x && foo()
?
推荐答案
AND 和 OR 运算符都可以快捷键.
所以 &&
仅在第一个表达式为真时才尝试第二个表达式(更具体地说,是真实的).第二个操作执行某些操作(无论 foo()
的内容如何)这一事实并不重要,因为它不会被执行除非第一个表达式的计算结果是真实的.如果是真的,那么将被执行以尝试第二次测试.
So &&
only tries the second expression if the first is true (truth-like, more specifically). The fact that the second operation does stuff (whatever the contents of foo()
does) doesn't matter because it's not executed unless that first expression evaluates to something truthy. If it is truthy, it then will be executed in order to try the second test.
相反,如果 ||
语句中的第一个表达式为真,则第二个表达式不会被触及.这样做是因为整个语句已经可以被计算,无论第二个表达式的结果如何,该语句都将返回 true,因此它将被忽略并保持未执行.
Conversely, if the first expression in an ||
statement is true, the second doesn't get touched. This is done because the whole statement can already be evaluated, the statement will result in true regardless of the outcome of the second expression, so it will be ignored and remain unexecuted.
使用这样的快捷方式时要注意的情况当然是运算符的情况,其中定义的变量仍然计算为假值(例如 0
)和真实值(例如 '零'
).
The cases to watch out for when using shortcuts like this, of course, are the cases with operators where defined variables still evaluate to falsy values (e.g. 0
), and truthy ones (e.g. 'zero'
).
这篇关于什么是“x&&"foo()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是“x&&"foo()"?


基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01