JavaScript成语:!某事&&功能() [英] JavaScript idiom: !something && function()

查看:87
本文介绍了JavaScript成语:!某事&&功能()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆