Foreword Switch expressions are found in many languages, such as Java, C wait, and using switch is more convenient and clearer than using if else.
The usage syntax is very simple:
switch (n)
{
case 1:
Execute code block 1
break;
case 2:
Execute code block 2
break;
default:
n Code that is not executed simultaneously with case 1 and case 2
}
The usage of various languages is basically similar.
If special mention is needed, in java 1.6 and below, the variable (n) can only be an integer. The String type is supported after Java 7.
In js, the String type can be used directly.
Usage examples
New Document
<script> <br>function funcSwitch(sFlag ) <br>{ <br>switch(sFlag) <br>{ <br>case "Test1": <br>alert("Test1"); <br>break; <br>case "Test2": <br> alert("Test2"); <br>break; <br>default:; <br>} <br>} <br><br>funcSwitch("Test2"); <br></script>
The logic is very simple and the code is very simple . Use string directly to distinguish.
The condition value corresponding to Case is also a variable If the corresponding value after case is not a string, but a variable. This can be achieved in combination with RegExp.
New Document < ;/TITLE>
<script> <br>var str1 = "Test1"; <br>var str2 = "Test1"; <br>function funcSwitch(sFlag) <br>{ <br>var regExp = new RegExp(sFlag); <br>switch(true) <br>{ <br>case regExp.test(str1): <br>alert( "Test1"); <br>break; <br>case regExp.test(str2): <br>alert("Test2"); <br>break; <br>default:; <br>} <br>} <br><br>funcSwitch("Test1"); <br><br></script>
< /BODY>