Overview
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
The break; statement is optional, and if you encounter break; the entire switch statement will pop up. If there is no case match, it goes to the branch of default:. default: The branch is also optional.
switch (expression) { case value1: // When the result of expression matches value1, start execution from herestatements1; [break;] case value2: // When the result of expression matches value2, start execution from herestatements2; [break;] ... case valueN: // When the result of expression matches valueN, start execution from herestatementsN; [break;] default: // If expression does not match the value above, execute the statement herestatements_def; [break;] }
Use condition judgment in case
Look at the code below, when foo is 0, 1, 2, 3, it shows alert.
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 following is obviously more concise and clear.
var foo = 1; switch (true) { // Non-variable TRUE replaces foocase foo >= 0 && foo <= 3: alert('yes'); break; default: alert('not'); }
Indicates a level
The carefully designed switch puts the least rarest conditions on top and the ordinary conditions on the lower side
function rankProgrammer(rank){ switch(rank){ case "advanced": = true; case "intermediate": = true; = true; case "primary": = true; = true; } } var xiaohu=new rankProgrammer("advanced"); (xiaohu);
The above content introduces the skills of switch statements to you, and I hope it will help you.