首页 > 解决方案 > 带有 javascript 条件运算符的 if 语句

问题描述

只有 2 个关于 JS 条件运算符的问题,下面的 2 个表达式是否有效?

1.

if(isUser && isUser === true || isGuest && isGuest === true){
     //...
   }

我想知道我是否必须添加 () 才能使它像并且仍然具有相同的功能:

if((isUser && isUser === true) || (isGuest && isGuest === true)){
     //...
   }
const items = list.orderList && list.orderList.isUser === true || list.orderList.isGuest ? list.items : [];

我想知道我是否必须添加 () 才能使其与上述条件运算符一样并且功能相同:

const items = list.orderList && (list.orderList.isUser === true || list.orderList.isGuest === true) ? list.items : [];

标签: javascriptif-statementconditional-statements

解决方案


根据MDN 文档中的运算符优先级,逻辑 AND 优先于逻辑 OR。所以,

expression1 || expression2 && expression3

将评估为

expression1 || (expression2 && expression3)

所以,

isUser && isUser === true || isGuest && isGuest === true

自然评估为

(isUser && isUser === true) || (isGuest && isGuest === true)

无论如何,所以你不需要括号..

但是,由于在您的第二个示例中,您想要评估 OR然后AND,您确实需要括号来评估您需要的方式,如

list.orderList && list.orderList.isUser === true || list.orderList.isGuest

将评估为

(list.orderList && list.orderList.isUser === true) || list.orderList.isGuest

推荐阅读