It has been said that a really good program is no if. Else, of course, switch is not as good as if. Else JS specification inside is prohibit to use switch.
The Command object is the perfect solution to the problem.
Referring to a foreign blog:
JavaScript has good control flow statements, which are often wrapped in curly braces. One exception: Switch ... case statement. Switch ... the strange thing about the case is that you have to add a keyword break at the end of each of the cases to prevent process control from crossing into the next statement. Crossing refers to the way that many cases are executed, and when the expected break is not met, control is automatically handed to the next case. However, just as with semicolons and curly braces, you are likely to inadvertently forget to write a break, and when this happens, later troubleshooting is more painful, because the statement itself is correct. So, pairing the case ... break is a good habit.
We usually say that JavaScript has elegant object literals and top-level functions that make a particular method query very simple. The object created for the method query, which we call the active object (Action object) or the command object, is used in many software design patterns, including powerful and useful command patterns.
Instance:
Copy Code code as follows:
Switch method
function Testswitch (name) {
Switch (name) {
Case ' 1 ':
return ' hack ';
Break
Case ' 2 ':
Return ' slash ';
Break
Case ' 3 ':
return ' run ';
Break
Default
return false;
Break
}
}
Using Command objects
function Testfn (name) {
var names = {
' 1 ': function () {
return ' hack ';
},
' 2 ': function () {
Return ' slash ';
},
' 3 ': function () {
return ' run ';
}
};
if (typeof Names[name]!== ' function ') {
return false;
}
return Names[name] ();
}
Test results
var result1 = Testswitch (' 1 ');
var result2 = testfn (' 2 ');
Console.info (RESULT1, RESULT2);