简体   繁体   中英

Why switch doesn't work while if statement does work

I need some help about what's wrong with switch in the following easy script.

var pp = 1;
switch (pp) {
    case pp == 1:
        var p = "A";
        break;
    default:
        var p = "F";
        break;
}

document.write(p); //display "F" ---??? it should be "A".

if (pp == 1) document.write("A"); //display "A"

You are using the switch - case syntax in a wrong way,

  switch(pp){
      case 1  : var p="A"; break;
      default : var p="F"; break;
  }

You could also write your code like below,

var p = pp ? "A" : "F"; //And this code is valid for your given data only.

You are re-evaluating the value of pp.

Should be

case 1:
....
break;

Javascript Switch-cause should follow this format

switch(expression) {
case n:
    code block
    break;
case n:
    code block
    break;
default:
    default code block
}

so,case pp==1 is in wrong format.it should be correct as follows

<script>
          var pp=1;
          switch(pp){
              case 1  : var p="A"; break;
              default : var p="F"; break;
          }
          document.write(p);

          if (pp==1) document.write("A");

   </script>

If you definitely need you make a reevaluation for every cases you can pass true as expression to the switch statement:

 var p, pp = 1; switch (true) { case pp === 1: p = 'A'; break; default: p = 'F'; } console.log(p); // p should be "A" if (pp === 1) { console.log('A'); // display "A" } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM