Why Switch statement only working with true keyword?

后端 未结 3 578
情书的邮戳
情书的邮戳 2021-01-22 20:33

Can anyone explain to me why first one is not working and second one is working?

First Statement

function test(n) {
    switch (n) {
    case (n         


        
3条回答
  •  死守一世寂寞
    2021-01-22 21:11

    switch is shorthand for a bunch of ifs.

    switch(n) {
        case x:
            a();
            break;
        case y:
            b();    
            break;
    }
    

    ... is equivalent to:

    if(n == x) {
         a();
    } else if(n == y) {
         b();
    }
    

    So your first piece of code:

    switch (n) {
       case (n==0 || n==1):
          console.log("Number is either 0 or 1");
          break;
    case (n>=2):
         console.log("Number is greater than 1")
         break;
    default:
        console.log("Default");}
    }
    

    ... is equivalent to:

    if(n == (n==0 || n==1)) {
       console.log("Number is either 0 or 1");
    } else if ( n == ( n >= 2)) {
       console.log("Number is greater than 1");
    } else {
       console.log("Default");
    }
    

    I hope you can see that n == (n==0 || n==1) and n == ( n >= 2) are both nonsense. If n is 0, for example, the first will evaluate to 0 == true. In many languages this will cause a compiler error (comparing different types). I don't especially want to think about what it does in Javascript!

    Your second example:

    switch (true) {
    case (n==0 || n==1):
       console.log("Number is either 0 or 1");
       break;
    case (n>=2):
       console.log("Number is greater than 1")
       break;
    default:
       console.log("Default");
    }
    

    Is equivalent to:

    if(true == (n==0 || n==1)) {
        console.log("Number is either 0 or 1");
    } else if(true == (n>=2)) {
        console.log("Number is greater than 1");
    } else {
        console.log("Default");
    }
    

    ... in which at least the condition statements true == (n==0 || n==1) and true == (n >=2) make sense.

    But this is an unconventional way to use switch in most languages. The normal form is to use the value you're testing as the parameter to switch and for each case to be a possible value for it:

    switch(n) {
        case 0:
        case 1:
             console.log("n is 0 or 1");
             break;
        case 2:
             console.log("n is 2);
             break;
        default:
             console.log("n is some other value");
    }
    

    However switch doesn't provide a cleverer case than a full equality check. So there's no case >2 && <5.

    Your can either use your trick using switch(true) (in Javascript -- there are many languages in which this won't work), or use if/else.

提交回复
热议问题