使用 && 的短路作为 if 语句?
我在 jQuery.form.js 源代码中看到这一行:
g && $.event.trigger("ajaxComplete", [xhr, s]);
我的第一个想法是 wtf?
我的下一个想法是,我无法决定这是丑陋还是优雅。
无论如何,我都不是 Javascript 专家,所以我的问题有两个。首先我想确认我正确理解了它。上面的行是否相当于:
if (g) {
$.event.trigger("ajaxComplete", [xhr, s]);
}
其次,这是 Javascript 中常见/接受的做法吗?一方面它很简洁,但另一方面,如果您以前没有见过它,它可能会有点神秘。
I saw this line in the jQuery.form.js
source code:
g && $.event.trigger("ajaxComplete", [xhr, s]);
My first thought was wtf??
My next thought was, I can't decide if that's ugly or elegant.
I'm not a Javascript guru by any means so my question is 2-fold. First I want to confirm I understand it properly. Is the above line equivalent to:
if (g) {
$.event.trigger("ajaxComplete", [xhr, s]);
}
And secondly is this common / accepted practice in Javascript? On the one hand it's succinct, but on the other it can be a bit cryptic if you haven't seen it before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,你的两个例子是等价的。它在几乎所有语言中都是这样工作的,但它在 Javascript 中变得相当惯用。我个人认为这在某些情况下是好的,但在其他情况下可能会被滥用。不过它肯定更短,这对于最小化 Javascript 加载时间很重要。
另请参阅 有人可以解释一下 John Resig 的 Pretty.js 吗? JavaScript 可以工作吗?
Yes, your two examples are equivalent. It works like this in pretty much all languages, but it's become rather idiomatic in Javascript. Personally I think it's good in some situations but can be abused in others. It's definitely shorter though, which can be important to minimize Javascript load times.
Also see Can somebody explain how John Resig's pretty.js JavaScript works?
这是标准的,但既不是 JSLint 也不是 JSHint 喜欢它:
It's standard, but neither JSLint nor JSHint like it:
您必须小心,因为如果条件中存在
||
,则可以绕过此短路:为避免这种情况,请务必对条件进行分组:
You must be careful because this short-circuiting can be bypassed if there is an
||
in the conditional:To avoid this, be sure to group the conditionals:
是的,它相当于您所写的
if
。这当然不是一种罕见的做法。是否被接受取决于谁在(或没有)接受......Yes, it's equivalent to an
if
as you wrote. It's certainly not an uncommon practice. Whether it's accepted depends on who is (or isn't) doing the accepting...是的,你明白(在这种情况下);是的,这是 JavaScript 中的标准做法。
Yes, you understand it (in that context); yes, it is standard practice in JavaScript.
默认情况下,它将触发 jshint 警告:
不过就我个人而言,我更喜欢短路版本,它看起来更具声明性并且具有“更少的控制逻辑”,但这可能是一种误解。
By default, it will trigger a jshint warning:
However personally, I prefer the short-circuit version, it looks more declarative and has "less control logic", might be a misconception though.