This article describes how to use a command object to replace the switch statement. The switch statement is forbidden in the JS specification. Using the command object can perfectly solve this problem, if you need a friend, you can refer to someone who once said that there is no such program .. else, of course, switch is not as good as if .. else. Switch is forbidden in JS specifications.
The command object solves this problem perfectly.
Reference a foreign blog:
JavaScript has good control flow statements, which are often enclosed in curly brackets. But there is one exception: switch... Case statement. Switch... The strange thing about case is that you must add the keyword break at the end of each case to prevent process control from traversing into the next case statement. Traversal refers to the method for executing multiple cases. When the expected break is not met, the control is automatically handed over to the next case. However, just like semicolons and curly braces, you are likely to forget to write break inadvertently. When this happens, troubleshooting will be painful in the future, because the statement itself is correct. Therefore, write case in pairing... Break is a good habit.
We usually say that JavaScript has an elegant object literal and top-level function, which makes the query of specific methods very simple. An object created for method query is called an action object or command object. It is used in many software design modes, including powerful and useful command modes.
Instance:
The Code is as follows:
// Switch method
Function testSwitch (name ){
Switch (name ){
Case '1 ':
Return 'hink ';
Break;
Case '2 ':
Return 'slash ';
Break;
Case '3 ':
Return 'run ';
Break;
Default:
Return false;
Break;
}
}
// Use the command object
Function testFn (name ){
Var names = {
'1': function (){
Return 'hink ';
},
'2': function (){
Return 'slash ';
},
'3': function (){
Return 'run ';
}
};
If (typeof names [name]! = 'Function '){
Return false;
}
Return names [name] ();
}
// Test Result
Var result1 = testSwitch ('1 ');
Var result2 = testFn ('2 ');
Console.info (result1, result2 );