javascript switch(true)

前端 未结 4 1655
别那么骄傲
别那么骄傲 2020-12-01 18:19

Hi i am trying to handle an ajax json response

here is my code

success: function (j) {     
    switch(true)
    {
        case (j.choice1):

                


        
相关标签:
4条回答
  • 2020-12-01 18:28

    It works for me:

    var a = 0, b = true;
        
    switch(true) {
        case a:
            console.log('a');
            break;
        case b:
            console.log('b');
            break;
    }

    However, the case labels must be equal to true, not jut implicitly true.
    Also, only the first case that evaluates to true will execute.

    0 讨论(0)
  • 2020-12-01 18:30

    In a case like this, a better way to do this is probably something like:

    success: function (j) {
        if(j.choice1 || j.choice2) {
            alert("choice2");
        } else {
            alert("default");
        }
    }
    
    0 讨论(0)
  • 2020-12-01 18:42

    SOLVED

    Based on SLaks answer i modify the code as below

        if(j.choice1){ var choice1=true;} else { var choice1=false;}
        if(j.choice2){ var choice2=true;} else { var choice2=false;}
    
        switch(true)
        {
            case choice1:
                alert("choice1");
            break;
            case choice2:
                alert("choice2");
            break;
            default:
                alert("default");
            break;
        }
    

    For all asking why switch and not if.

    Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).

    The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute

    Thank to all

    0 讨论(0)
  • 2020-12-01 18:49

    You need to read up on the switch statement. You should not be switching on a constant value.

    It appears that you need to use if statements, as you don't really want to be switching on your j value:

    success: function (j) {     
        if (j.choice1)
        {
            alert("choice1");
            break;
        }
    
        if (j.choice2)
        {
            alert("choice2");
            break;
        }
    
        alert("default");
      }
    }
    
    0 讨论(0)
提交回复
热议问题