javascript - 带有 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 : [];
解决方案
根据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
推荐阅读
- graphics - Graphics.set_font Ocaml
- intellij-idea - 在 IntelliJ 上使用 glassfish(payara) 服务器的 web.xml 错误
- c# - 将 asp.net 核心自包含 Web 应用程序部署到 Ubuntu。数据库名称在 appsettings.json 中存在时为空
- r - 命令行等效于 RStudio 中的“构建源包”
- makefile - GNU make:如何防止“-include file.ext”执行目标为“file.ext”的规则?
- excel - 将 XBRL 事实提取到 Excel
- java - JavaFX:用线程移动一个圆圈
- swift - 从 UIImagePicker 将图像上传到 Firebase
- java - Recusion - 计算混合字符串中的数字总和。(作业死胡同)
- tig - 如何用一行绑定多个键盘映射?