JavaScript成语:!某事&&功能() [英] JavaScript idiom: !something && function()
问题描述
我一直在查看 raphael.js 的源代码,我看到很多像!变量&& function()
(例如:!svg.bottom&&(svg.bottom = this);
)
I have been looking at the source code of raphael.js and I see a lot of stuff like !variable && function()
(e.g.: !svg.bottom && (svg.bottom = this);
)
这究竟是做什么的?它是先检查并仅在不是真的情况下执行吗?
What does that exactly do? Does it check first and execute only if not true?
推荐答案
正确。这是(ab)使用短路评估。布尔表达式仅在确定结果所需的范围内执行。在您的示例中,如果 svg.bottom
为非null,则!svg.bottom
为 false
,&&
的结果是 false
,因此执行右手边没有发生。它基本等同于 if(!svg.bottom)svg.bottom = this;
Correct. This is (ab)using short-circuit evaluation. A boolean expression is only executed as far as is needed to determine the result. In your example, if svg.bottom
is non-null, then !svg.bottom
is false
, and the result of the &&
is false
, so execution of the right hand side does not happen. It's basically equivalent to if(!svg.bottom)svg.bottom = this;
这篇关于JavaScript成语:!某事&&功能()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!