真值表时间!
A 是MyValue*
B 是window.ExtraObject**
C 是ExtraObject.ExtraBool
A B C | O
------+--
0 0 0 | 0
0 0 1 | 0
0 1 0 | n/a***
0 1 1 | 0
1 0 0 | 1
1 0 1 | n/a***
1 1 0 | 1
1 1 1 | 0
我们从这些值中发现,最简单的方程式O是:
A && !C
所以你的代码应该是:
if (MyValue && !ExtraObject.ExtraBool) {}
ExtraObject但是,当然,您提到如果未定义不想遇到问题:
var extraBool = window.ExtraObject ? ExtraObject.ExtraBool : false;
if (MyValue && !extraBool) {}
另一种写作extraBool方式是:
var extraBool = window.ExtraObject && ExtraObject.ExtraBool;
然后你可以内联这个:
if (MyValue && !(window.ExtraObject && ExtraObject.ExtraBool)) {}
写作的另一种选择!(a && b)是!a || !b,这意味着:
if (MyValue && (!window.ExtraObject || !ExtraObject.ExtraBool)) {}
也是正确的。
* 这可能MyValue===true取决于您需要的严格程度
** 或者typeof ExtraObject !== 'undefined'
*** 实际上不可能有ExtraObject未定义和访问权限ExtraObject.ExtraBool