Home > Article > Web Front-end > Detailed explanation of usage examples of switch statements and expressions in JavaScript
The format of the stwith statement is generally as follows:
switch (expression){ case value :statement1 break; case value2 :statement2 break; .... case value: statement break; default :statement;
Each case indicates that if the value of expression is equal to case, then the statistics.
The keyword break causes the code to jump out of switch.
If there is no keyword break, the code will continue to execute the next situation. The keyword default is the result of execution when the value of all expressions is not equal to the value value.
iwork = parseInt(prompt("请输入1-5的值")); switch (iwork) { case 1 :document.write("星期一") break; case 2 : "星期2" break; case 3 : "星期3" break; case 4 : "星期4" break; case 5 : "星期5" break; default :"要输入合理值";
In js, the String type can be used directly.
Usage example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Author" CONTENT="oscar999"> <script> function funcSwitch(sFlag) { switch(sFlag) { case "Test1": alert("Test1"); break; case "Test2": alert("Test2"); break; default:; } } funcSwitch("Test2"); </script> </HEAD> <BODY> </BODY> </HTML>
The condition value corresponding to Case is also a variable
If the corresponding value behind the case is not a string, but a variable. This can be achieved in combination with RegExp.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Author" CONTENT="oscar999"> <script> var str1 = "Test1"; var str2 = "Test1"; function funcSwitch(sFlag) { var regExp = new RegExp(sFlag); switch(true) { case regExp.test(str1): alert("Test1"); break; case regExp.test(str2): alert("Test2"); break; default:; } } funcSwitch("Test1"); </script> </HEAD> <BODY> </BODY> </HTML>
The above is the detailed content of Detailed explanation of usage examples of switch statements and expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!