Someone once said that a really good program does not have if..else, of course switch is not as good as if..else. The use of switch is prohibited in the JS specification.
The command object perfectly solves this problem.
Quote a foreign blog:
JavaScript has good control flow statements, which are often wrapped in curly braces. But there is an exception: switch … case statement. The weird thing about switch … case is that you have to add the keyword break at the end of each case to prevent process control from traveling through to the next case statement. Time travel refers to the method of allowing multiple cases to be executed. When the expected break is not encountered, the control will be automatically handed over to the next case. However, just like semicolons and curly braces, you may inadvertently forget to write breaks. When this happens, later error checks are more painful because the statement itself is correct. Therefore, it is a good habit to write case … break in pairs.
We usually say that JavaScript has elegant object literals and top-level functions, which make specific method queries very simple. The object created for method queries, we call it an active object or a command object, which is used in many software design patterns, including powerful and useful command patterns.
Example:
The code copy is 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;
}
}
// Use the command object
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);