哪个逻辑运算符优先 [英] Which Logic Operator Takes Precedence

查看:173
本文介绍了哪个逻辑运算符优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在研究在if-else语句中用逻辑运算符编写稍微复杂的操作。我知道我可以做括号,我知道这是更好的方法,但我已经好奇,所以我会问。如果我要做这样的事情:

So, I'm looking into writing a slightly more complex operation with logic operators in an if-else statement. I know I can do parentheses, and I know it's the better way of doing this, but I've gotten curious and so I'm going to ask. If I were to do something like this:

if (firstRun == true || selectedCategory != undefined && selectedState != undefined) {
//Do something
} else {
//Do something else
}

如何在不使用括号的情况下进行操作?我知道逻辑运算符有一个操作顺序,类似于PEMDAS,对吗?我很好奇它是否会像这样运行:

How will that be operated without the use of parentheses? I know there is an order of operations for logic operators, similar to PEMDAS, right? I'm curious if it'll be ran something like this:

firstRun == true || (selectedCategory != undefined && selectedState != undefined)

或者如果'或'运算符优先于它,最终结果如下:

or maybe if the 'OR' operator takes precedence instead and it ends up going like:

(firstRun == true || selectedCategory != undefined) && selectedState != undefined

如果你能在某个地方找到它,那么完整列表会很好对此的操作。谢谢!

The full list would be nice, if you can find it somewhere, of the order of operations for this. Thanks!

推荐答案

我的经验法则基本上涵盖了条件语句的所有用例的99%,是:

My rule of thumb, which covers basically 99% of all use cases for conditional statements, is:


  1. 分组:()

  2. 会员访问。或[...]

  3. 不:

  4. 比较,例如< ,> =,===,!=,...

  5. 逻辑AND &&

  6. 逻辑或 ||

  1. Grouping: ()
  2. Member access . or [...]
  3. Not: !
  4. Comparison, e.g. < , >= , === , !=, ...
  5. Logical AND &&
  6. Logical OR ||

MDN为您提供详尽的细分: Javascript Operator Precedence

MDN gives you the exhaustive breakdown: Javascript Operator Precedence

所以对于你的例子:

(firstRun == true || selectedCategory != undefined && selectedState != undefined)

等于

(firstRun == true) || ((selectedCategory != undefined) && (selectedState != undefined))

还有更多比上面提到的情况复杂,我会考虑为可读性重构代码!

For anything more complex than the above mentioned cases I would look into refactoring the code for readabilities sake anyways!

这篇关于哪个逻辑运算符优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆