Home > Article > Web Front-end > A brief introduction to the switch statement in JavaScript (with code)
This article brings you a brief introduction to the switch statement in JavaScript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
JavaScriptswitch statement
The switch statement is used to perform different actions based on different conditions.
JavaScript switch statement
Use the switch statement to make multiple selections.
Syntax:
switch( 变量1 ){ case 变量2: //语句1; break; case 变量3: //语句2; break; default: //语句3; }
Execution principle: The value of variable 1 is compared with the value of case. For example, if variable 1 is equal to case variable 2, statement 1 will be executed. If variable 1 is equal to case variable 3, execute statement 2. If neither match, execute statement 3.
break ends the currently executing statement. default Default is selected by default when there is no matching option.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> </body> <script type="text/javascript"> var num = 3; switch (num) { case 0: alert("0"); break; case 1: alert("1"); break; case 2: alert("2"); break; case 3: alert("3"); break; case 4: alert("4"); break; default: alert("默认选项"); break; } //当num等于0,执行alert("0");......如果都不匹配,就执行alert("默认选项"); </script> </html>
default keyword When all options do not match, the code of the default option is executed by default.
The above is the detailed content of A brief introduction to the switch statement in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!