javascript multiple OR conditions in IF statement

2020-02-03 06:33发布

I think I'm missing something basic here. Why is the third IF condition true? Shouldn't the condition evaluate to false? I want to do something where the id is not 1, 2 or 3.

var id = 1;
if(id == 1) //true    
if(id != 1) //false 
if(id != 1 || id != 2 || id != 3) //this returns true. why?

Thank you.

标签: javascript
6条回答
家丑人穷心不美
2楼-- · 2020-02-03 06:47

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

查看更多
该账号已被封号
3楼-- · 2020-02-03 06:48

This is an example:

false && true || true   // returns true
false && (true || true) // returns false
(true || true || true)  // returns true
false || true           // returns true
true || false           // returns true
查看更多
成全新的幸福
4楼-- · 2020-02-03 06:54

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

查看更多
男人必须洒脱
5楼-- · 2020-02-03 06:56

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

which translates to

if (id !== 1 && id !== 2 && id !== 3)

or alternatively for something more pythonesque:

if (!(id in [,1,2,3]))
查看更多
我想做一个坏孩纸
6楼-- · 2020-02-03 06:59

When it checks id!=2 it returns true and stops further checking

查看更多
一夜七次
7楼-- · 2020-02-03 07:03

Each of the three conditions is evaluated independently[1]:

id != 1 // false
id != 2 // true
id != 3 // true

Then it evaluates false || true || true, which is true (a || b is true if either a or b is true). I think you want

id != 1 && id != 2 && id != 3

which is only true if the ID is not 1 AND it's not 2 AND it's not 3.

[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.

查看更多
登录 后发表回答