The switch statement is used to execute different actions based on different conditions.
JavaScript switch statement
The switch statement is used to execute different actions based on different conditions.
JavaScript switch statement
Use the switch statement to select one of the multiple code blocks to be executed.
Syntax
Switch (n) {case 1: Execution Code Block 1 break; case 2: Execution Code Block 2 break; default: Code executed differently between n and case 1 and case 2}
Working principle: first set expression n (usually a variable ). Then the expression value is compared with the value of each case in the structure. If a match exists, the code block associated with the case will be executed. Use break to prevent code from automatically running to the next case.
Instance
The name of the day of the week is displayed. Please note that Sunday = 0, Monday = 1, Tuesday = 2, and so on:
var day=new Date().getDay();switch (day){case 0: x="Today it's Sunday"; break;case 1: x="Today it's Monday"; break;case 2: x="Today it's Tuesday"; break;case 3: x="Today it's Wednesday"; break;case 4: x="Today it's Thursday"; break;case 5: x="Today it's Friday"; break;case 6: x="Today it's Saturday"; break;}
X running result:
Today it's Saturday
Default keyword
Use the default keyword to specify what to do when the match does not exist:
Instance
If today is not Saturday or Sunday, the default message will be output:
var day=new Date().getDay();switch (day){case 6: x="Today it's Saturday"; break;case 0: x="Today it's Sunday"; break;default: x="Looking forward to the Weekend";}
Running result of x
Today it's Saturday
The above is the content of the JavaScript switch statement in the [JavaScript tutorial]. For more information, see the PHP Chinese website (www.php1.cn )!