简体   繁体   English

或在三元运算符中,使用&&

[英]OR in ternary operator, using &&

Using the traditional if statement I can do this: 使用传统的if语句,我可以这样做:

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

But when I try to do something the same thing with a ternary operator, like this: 但是,当我尝试使用三元运算符执行相同操作时,如下所示:

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

I just get errors about unexpected ||. 我只是收到有关意外||的错误。

According to this answer: Precedence: Logical or vs. Ternary operator , we can do it using 根据以下答案: 优先级:逻辑或对三元运算符 ,我们可以使用

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

(Sorry I'm not sure how to call the ? : symbols in this case), but I'm not sure how to get it running using && (It means only run the code if returned true ). (对不起,在这种情况下,我不确定如何调用? :符号),但是我不确定如何使用&&使它运行(这意味着仅在返回true运行代码)。

I created a codepen to test it easily. 我创建了一个Codepen来对其进行轻松测试。 Here's the whole code: 这是整个代码:

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 这是链接

Just take parenthesis to prevent operator precedence of && over || 只需加上括号以防止&&优先于||

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

Without parenthesis, you get (now with to show the precedence) a different result. 没有括号,您将获得不同的结果(现在可以使用来显示优先级)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM