Javascript 条件订单评估

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5891754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:42:09  来源:igfitidea点击:

Javascript conditional order evaluation

javascript

提问by atp

Can I count on Javascript failing immediately when one condition in an expression results to false?

当表达式中的一个条件结果为 false 时,我可以指望 Javascript 立即失败吗?

f = {'a':'b'};
if (f.a !== undefined || f.a === 'b') {
  // Is this OK to use, because the second condition will never be evaluated?
}

回答by alex

Yes, this is known as short circuit evaluation.

是的,这就是所谓的短路评估

With an ANDlogical operator, if the first evaluates to false, then the second is never evaluated, because the condition knows enough already to be met.

对于AND逻辑运算符,如果第一个计算结果为false,则永远不会计算第二个,因为条件已经足够满足。

With the ORlogical operator, if the first one is false, it will evaluate the second one. Otherwise if the first is trueit won't evaluate the second (no need to).

使用OR逻辑运算符,如果第一个是false,它将评估第二个。否则,如果第一个是true它不会评估第二个(不需要)。

This is also why you see...

这也是为什么你看到...

var a = function(b) {
   b = b || 7;
}