Description: Executes different code according to the different values of a variable.
Syntax structure:
Switch (variable)
{
Case value 1:
Code 1;
Break
Case Value 2:
Code 2;
Break
Case Value 3:
Code 3;
Break
Default
If none of the above conditions are met, execute the code;
}
Switch Structure Description:
Switch, case, break, and default are all system keywords and must all be lowercase.
Switch parentheses (): Parentheses are typically a variable name, and this variable may have different values.
The value of each case, which is compared to the value of the variable, executes the code after it, if it is consistent.
All case is a "or" relationship, and only one case at a time satisfies the condition.
After the code in each case executes, it must end with the break statement, and after the end, the program will jump to the switch end brace and run.
If you do not write a break statement, all of the following case statements will be executed again.
Example: Output today is the day of the week
/*
(1) Create a DateTime object with a lot of information: hours, minutes, seconds, year, month, day, week
(2) Remove the day of the week value from the Date object
(3) The weekday value (0-6) to output the day of the week in Chinese
*/
(1) Create a System datetime object, where date () is a system function and the first letter is capitalized
var today = new Date ();
(2) Remove the week value from the Date object
var week = Today.getday (); Returns 0-6, 0 for Sunday
(3) Use switch to output the day of the week
var str;
Switch (week)
{
Case 1:
str = "one";
Break
Case 2:
str = "two";
Break
Case 3:
str = "three";
Break
Case 4:
str = "four";
Break
Case 5:
str = "Five";
Break
Case 6:
str = "Six";
Break
Default
str = "Day";
}
(4) Output results
document.write ("Today is the Week" +STR)
if Multi-conditional judgment and Switch the Difference
The condition in the if is generally a range (a>100), and the condition in switch is generally a different value for a variable.
Switch Branch statement