javascript switch(true)

前端 未结 4 1680
别那么骄傲
别那么骄傲 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: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

提交回复
热议问题