OR 三元运算符,使用 &&

OR in ternary operator, using &&

使用传统的 if 语句我可以做到这一点:

if(a===0 || b===0) {console.log('aloha amigo')};

但是当我尝试用三元运算符做同样的事情时,像这样:

a===0 || b===0 && console.log('aloha amigo')

我只是收到有关意外 || 的错误。

根据这个答案:,我们可以使用

condition1 || condition2 ? do if true : do if false

(抱歉,我不确定在这种情况下如何调用 ? : 符号),但我不确定如何使用 && 获得它 运行ning(如果返回 true).

,则仅表示 运行 代码

我创建了一个代码笔来轻松测试它。这是完整的代码:

var a = 0;
var b = 1;

a===0 || b===0 ? console.log('Works here') : console.log('And here');

a===0 || b===0 && console.log('Doesn\'t work here');

a===0 && console.log('The && works for a single test');

Here's the link

只是用括号来防止 && 的运算符优先于 ||

(a === 0 || b === 0) && console.log('aloha amigo')

没有括号,你会得到(现在用 来显示优先级)不同的结果。

a === 0 || (b === 0 && console.log('aloha amigo'))
^^^^^^^                                             first evaluation
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  second evaluation