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 不同时执行的代码 }
Working principle: First set the expression n (usually a variable). The value of the expression is then compared to 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
Displays today’s week name. Please note that Sunday=0, Monday=1, Tuesday=2, etc.:
php中文网(php.cn) 点击下面的按钮来显示今天是周几:
Run the program and try it
default Keywords
Please use the default keyword to specify what to do when the match does not exist:
Example
If today If it is not Saturday or Sunday, the default message will be output:
php中文网(php.cn) 点击下面的按钮,会显示出基于今日日期的消息:
Run the program and try it