Encounter a strange problem, the switch statement condition should be established, but it is true that default, can be directly used with if, this is why?

now there are three components, A component, B component and C component
when I jump from A component to B component, B component writes

    beforeCreate(){
      let status=this.$route.query.status;
       switch (status){
           case 1: document.title=""
               break;
           case 2: document.title=""
               break;
           case 3: document.title="";
               break;
           default:
           console.log(status == 1);
            document.title="";
               break;
       }
    },

the name of the browser changes, but when I jump from component B to component C, when I jump from component C to component B, the name of the browser changes to-- (because the name of the title of component B is dynamic, I change the initial value to -)

clipboard.png

so now the switch equal to 1 is not executed, and what I print in default also returns true
why not execute it?
I can just change to the if statement, but why not execute the case equals 1 in switch?

    beforeCreate(){
        //title
        let status=this.$route.query.status;
        if(status == 1){
            document.title=""
        }else if(status == 2){
            document.title=""
        }else if(status == 3){
            document.title=""
        }
      },

I am curious about what causes this problem.

Mar.29,2021

because the value of your statsu is the string "1" , while the case is the number 1 , case use = to make a strict comparison. The if statement uses = = to make non-strict comparisons, which automatically converts types.

either write all the numbers in case into strings, or let status = parseInt (this.$route.query.status, 10); convert status to integers.

What is required in

case is constant, which generally cannot be judged logically, so this is where if statements are superior to switch statements!

Menu