Javascript&&如果第一个表达式为真,则为运算符 [英] Javascript && operator if first expression is true

查看:127
本文介绍了Javascript&&如果第一个表达式为真,则为运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我正在检查是否使用if执行代码块.第一个表达式为true或false,但是第二个表达式也可以为其他表达式.我想知道是否有任何方法可以忽略&&&中的第二个表达式如果第一个表达式已经为真,则为运算符.

我希望这个例子有助于澄清:

In my code I am checking whether or not to execute a block of code using if. The first expression is either true or false, but the second can also be something else. I was wondering whether there is any way to ignore the second expression in a && operator if the first expression is already true.

I hope this example helps in clearifying:

var a = true;
var b = someFunction(); // This returns an object with a boolean property, but can also undefined in some cases
if(a && b.someValue) {
 // do something
}



当b未定义时,将引发错误.但是,如果a已经为真,是否有一种方法可以不对b.someValue求值,因为该值对于if子句不再重要了?在a为true的情况下,由于b.someValue不需要评估,因此错误是不必要的.

谢谢.



When b is undefined, it raises an error. However, if a is already true, is there a way not to evaluate b.someValue as that value doesn''t matter anymore for the if clause? In the case a is true, the error is unnecessary as b.someValue doesn''t need to be evaluated.

Thanks.

推荐答案

在这种情况下,将&&更改为||. (或).
In that case change && to || (or).


这篇关于Javascript&&如果第一个表达式为真,则为运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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