why I get Different result in switch statements

后端 未结 3 797
一个人的身影
一个人的身影 2021-01-15 14:39

I am learning JavaScript and currently I build simple tip calculator using function and switch statement. Basically, tip 20% of the bill when the bill is less than $50, 15%

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 14:53

    switch case does not work the way you are using it.

    switch(test){
        case a:
            break;
        case b:
            break;
        case c:
            break;
    }
    
    

    compares the value of test to the value of a, then b and so on

    so in your first code example it compares 124 with the value/output of (bill > 0 && bill < 50) which is false

    so you are comparing integers with booleans.
    To make ranges work you have to do it like in your second example.

    Stackoverflow post I found: https://stackoverflow.com/a/5619997/7584725

提交回复
热议问题