使用&&&&&'s的短路作为if语句? [英] Using &&'s short-circuiting as an if statement?
问题描述
我在 jQuery.form.js
源代码中看到了这一行:
I saw this line in the jQuery.form.js
source code:
g && $.event.trigger("ajaxComplete", [xhr, s]);
我的第一个想法是wtf ??
My first thought was wtf??
我的下一个想法是,我无法确定这是丑陋还是优雅。
My next thought was, I can't decide if that's ugly or elegant.
我不是任何方式的Javascript大师所以我的问题是2倍。首先,我想确认我理解正确。以上行是否相当于:
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]);
}
其次是Javascript中常见/接受的做法?一方面它很简洁,但另一方面,如果你以前没见过它,它可能有点神秘。
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.
推荐答案
是的,你的两个例子是等价的。它在几乎所有语言中都是这样的,但它在Javascript中变得相当惯用。我个人认为在某些情况下这种情况很好但在其他情况下可能会被滥用。它肯定更短,这对于最小化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.
另见有人可以解释John Resig的pretty.js JavaScript是如何工作的吗?
这篇关于使用&&&&&'s的短路作为if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!