Home >Web Front-end >JS Tutorial >[JavaScript Tutorial] JavaScript switch statement
JavaScript switch statement
switch statement is used to perform different actions based on different conditions.
JavaScript switch statement
Use the switch statement to select one of multiple blocks of code to execute.
Syntax
switch(n) { case 1: 执行代码块 1 break; case 2: 执行代码块 2 break; default: n 与 case 1 和 case 2 不同时执行的代码 }
How it works: First set the expression n (usually a variable). The value of the expression is then compared with the value of each case in the structure. If there is a match, the code block associated with the case is executed. Please use break to prevent the code from automatically running to the next case.
Example
Show today’s week name. Please note that Sunday=0, Monday=1, Tuesday=2, etc.: The result of
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 is:
Today it's Saturday
default keyword
Please use the default keyword to specify what to do when the match does not exist:
Example
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"; }
x’s running results
Today it's Saturday
The above is the content of the JavaScript switch statement in [JavaScript Tutorial]. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!