使用传统的 if 语句,我可以做到这一点:
if(a===0 || b===0) {console.log('aloha amigo')};
但是当我尝试用三元运算符做同样的事情时,像这样:
a===0 || b===0 && console.log('aloha amigo')
我只是收到有关意外 || 的错误。
根据这个答案:Precedence: Logical or vs. Ternary operator ,我们可以使用
condition1 || condition2 ? do if true : do if false
(抱歉,我不知道在这种情况下如何调用
? :
符号),但我不知道如何使用 &&
让它运行(这意味着只有返回 true
时才运行代码)。我创建了一个 codepen 来轻松测试它。这是整个代码:
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
关于javascript - OR 在三元运算符中,使用 &&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51206667/