javascript multiple OR conditions in IF statement

前端 未结 6 833
刺人心
刺人心 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 11:44

    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
    
    0 讨论(0)
  • 2020-12-08 11:48

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

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

    0 讨论(0)
  • 2020-12-08 11:50

    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.

    0 讨论(0)
  • 2020-12-08 11:52

    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]))
    
    0 讨论(0)
  • 2020-12-08 12:00

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题