Tips for Switch statements

  • 2020-05-14 04:59:06
  • OfStack

An overview of the

The switch statement evaluates an expression, compares the result with the case substatement, and, if it matches, executes downward from the statement at case.

grammar

break; Statements are optional if encountered with break; The whole switch statement pops up. If there are no case matches, go to the branch of default:. default: branches are also optional.


switch (expression) {
case value1:
//  when  expression  With the result of the  value1  When a match is made, it is executed from here 
statements1 ; 
[break;]
case value2:
//  when  expression  With the result of the  value2  When a match is made, it is executed from here 
statements2;
[break;]
...
case valueN:
//  when  expression  With the result of the  valueN  When a match is made, it is executed from here 
statementsN;
[break;]
default:
//  if  expression  With the above  value  When the values do not match, execute the statement here 
statements_def;
[break;]
}

Conditional judgment is used in case

Look at the code below to display alert when foo is 0,1,2,3.


var foo = 1;
switch (foo) {
case 0:
case 1:
case 2:
case 3:
alert('yes');
break;
default:
alert('not');
}

Is there a better way to write it? The next one is clearly cleaner.


var foo = 1;
switch (true) { //  invariant  TRUE  alternative  foo
case foo >= 0 && foo <= 3:
alert('yes');
break;
default:
alert('not');
}

Said level

The well-designed switch places _ the least and rarest of conditions _ at the top, with common conditions placed relative to the bottom


function rankProgrammer(rank){ 
switch(rank){ 
case " senior ": 
this.secretary = true;
case " The intermediate ": 
this.laptop = true;
this.bonus = true;
case " primary ": 
this.salary = true;
this.vacation = true; 
}
}
var xiaohu=new rankProgrammer(" senior ");
console.log(xiaohu);

The above content gives you the switch statement skills, I hope to help you above.


Related articles: