Overview
The switch statement evaluates to an expression, compares the result with the case child, and, if it matches, executes down from the statement at which it was executed.
Grammar
break; The statement is optional, and if a break is encountered, the entire switch statement is jumped out. If there is no case match, go to the branch of default: Default: The branch is also optional.
switch (expression) {
case value1:
//When the result of expression matches value1, start statements1 from this place
;
[break;]
Case value2:
//When the results of the expression match with the value2, the statements2 is executed from here
;
[Break;]
...
Case Valuen:
//When the results of the expression match with the Valuen, the STATEMENTSN is executed from here
;
[Break;]
Default:
//If expression does not match the value above, execute the statement
statements_def here;
[Break;]
}
Judging the conditions of use in case
Look at the following code, which displays alert when Foo is 0,1,2,3.
var foo = 1;
Switch (foo) {case
0: Case
1: Case
2: Case
3:
alert (' yes ');
break;
Default:
alert (' not ');
Is there any better way to spell it? The following is obviously more concise and clear.
var foo = 1;
Switch (TRUE) {//non-variable true replaces foo case
foo >= 0 && foo <= 3:
alert (' yes ');
break;
Default:
alert (' not ');
Presentation level
Carefully designed switch put _ at least the most rare conditions _ above, the normal conditions placed in the position relative to the following
function Rankprogrammer (rank) {
switch (rank) {Case
"advanced":
this.secretary = true;
Case "Intermediate":
This.laptop = true;
This.bonus = true;
Case "PRIMARY":
this.salary = true;
This.vacation = true;
}
}
var xiaohu=new rankprogrammer ("advanced");
Console.log (Xiaohu);
The above content has introduced the switch statement the skill, hoped for everybody above help.