javascript multiple OR conditions in IF statement

前端 未结 6 849
刺人心
刺人心 2020-12-08 11:17

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

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 12:07

    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.

提交回复
热议问题