The general usage of a switch statement is simple, as follows:
var a = 3;
Switch (a) {case
1:
Console.log (a);
break;
Case 2: Case
3:
Console.log (a);
break;
Default: Break
;
}
Here A and case list from the top down to do the comparison, if the match on the execution of the code, if there is a break jump, no break will continue to match until the new match and break or switch code block end.
Attention:
A and case values of the matching algorithm is to perform strict equality comparison (' = = '), usually a and case values are simple values.
The value of the case can be a variety of expressions in addition to the simple value, switch (a) {...} The A will be compared to the result value of the expression in the case ("= ="), from which we can:
var a = [4], B = ' 3 ';
function foo (A, b) {return
Math.Abs (a-b) < 2;
}
Switch (true) {case
! ( A && B: //filter out a,b where there is a ' false value ' situation
console.log (' A: ' +a, ' B: ' +b);
break;
Case Foo (a,b): //When the a,b difference is within 2, the Foo function returns true
console.log (' A-b < ' +math.abs (a-b));
case a = = B:
console.log (A + ' = = ' +b);
break;
Case a < b:
Console.log (A + ' < ' +b);
break;
Case a > B:
console.log (A + ' > ' +b);
break;
Default: Break
;
}
In the above example, true is strictly equal to the value of the expression for each case and only matches if the value of the instance expression is Boolean true, and any other truth does not match.
Note:case! (a && B): Must put &&, | | The result of the operator is converted to a Boolean value to match (because &&, | | The return value of the expression is not a Boolean type, it returns the value of the first true, or false first in the expression.
So, as long as you want to get, as long as the rules, can be implemented with switch! Just don't know how to write code so good!
The above is small series for everyone to bring the switch statement of the magical magic (must see article) all content, I hope that we support cloud Habitat Community ~