JavaScript switch statement
JavaScript switch
JavaScript switch allows selection of multiple possible results of a scalar (expression).
Syntax:
switch (expr) {
case result1:
statement1
break;
case result2:
statement2
break;
……
default:
statement
}
Syntax explanation
The system calculates expr Value, select and execute the corresponding statement below based on the calculation results (result1, result2, etc.). If all case results do not match, the statement in default will be executed.
break is used to jump out of the process after executing the code. Although it can be omitted grammatically, do not omit it except in special circumstances. Otherwise, the following code will continue to be executed, even if the calculated expr result does not match the case (this is the same as if else difference).
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var x = 2; switch (x) { case 0: alert("x等于0"); break; case 1: alert("x等于1"); break; case 2: alert("x等于2"); break; default: alert("x既不等于1和2,也不等于0"); } </script> </head> <body> </body> </html>
Tips
There can be multiple case conditional judgments
case The subsequent results are not limited to numbers, but also Is a character or other type supported by JavaScript
default keyword
Please use the default keyword to specify what to do when the match does not exist:
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { var x; var d=new Date().getDay(); switch (d) { case 6:x="今天是星期六"; break; case 0:x="今天是星期日"; break; default: x="期待周末"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>