Javascript multiple or condition check

前端 未结 4 1678
暗喜
暗喜 2021-01-29 06:44

I have struck with some simple if else checking

var IsCompanyContacttitleUpdate = false;
var ContactStatus = -1;

if ((IsCompanyContacttitleUpdate == false) &am         


        
相关标签:
4条回答
  • 2021-01-29 07:08

    (ContactStatus == 2 || 3 || 4))

    Here is your problem. You are saying if ContactStatus equals 2, it is true, OR true OR true.

    False = 0, True is anything not 0.

    You need to rewrite that as:

    (ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4))

    It should work if you change that one thing

    0 讨论(0)
  • 2021-01-29 07:11

    Would this work? I changed the if condition from (ContactStatus == 2 || 3 || 4) to ((ContactStatus == 2) || (ContactStatus == 3) || (ContactStatus == 4)).

    (ContactStatus == 2 || 3 || 4) evaluates (ContactStatus == 2); since it's true, it evaluates 3 as a condition. Since 3 is different from 0 (zero), then is results as true; and the whole OR evaluates to true. The final result is that the whole if condition is true and the "then" branch is selected.

    var IsCompanyContacttitleUpdate = false;
    var ContactStatus = 6;
    
    if ((IsCompanyContacttitleUpdate == false) && ((ContactStatus == 2) || (ContactStatus == 3) || (ContactStatus == 4))) 
    {
        alert('inside if')
    } else if (IsCompanyContacttitleUpdate == false && ContactStatus == 2) {
        alert('inside else if')
    } else {
        alert('yup yup else');
    
    }
    
    0 讨论(0)
  • 2021-01-29 07:12

    the problem is (ContactStatus == 2 || 3 || 4)

    the correct way should (ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4)

    0 讨论(0)
  • 2021-01-29 07:35

    This ContactStatus == 2 || 3 || 4 is invalid (maybe invalid is not the correct word, to be more accurate let's say that it's not doing what you think it does)

    For your scenario you'll need to use

    ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4
    

    Your code could be tranlated to

    ContactStatus == 2 || true || true
    

    And this is always true.

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