Switch expressions are available in many languages, such as java and C waiting. It is easier and clearer to use switch than to use ifelse. The following describes how to use it in detail, if you are interested, refer
Preface
The switch expression is available in many languages, such as java and C waiting. It is easier and clearer to use switch than to use if else.
The syntax is simple:
The Code is as follows:
Switch (n)
{
Case 1:
Execution Code Block 1
Break;
Case 2:
Execution Code Block 2
Break;
Default:
Code executed at different times between n and case 1 and case 2
}
The usage of various languages is similar.
In java 1.6 and earlier versions, 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.
Use instance
The Code is as follows:
New Document
Script
Function funcSwitch (sFlag)
{
Switch (sFlag)
{
Case "Test1 ":
Alert ("Test1 ");
Break;
Case "Test2 ":
Alert ("Test2 ");
Break;
Default :;
}
}
FuncSwitch ("Test2 ");
Script
The logic is simple, and the code is simple. Use string directly to differentiate.
The condition value corresponding to Case is also a variable.
If case is followed by a variable instead of a string. It can be achieved in combination with RegExp.
The Code is as follows:
New Document
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