Bam*_*ert 19 javascript switch-statement
我不想在我的代码中使用Switch,所以我正在寻找一些替代方案
Switch的示例:
function write(what) {
switch(what) {
case 'Blue':
alert ('Blue');
break;
...
case 'Red':
alert ('Red');
break;
}
}
Run Code Online (Sandbox Code Playgroud)
没有Switch的示例:
colors = [];
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
colors[what]();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
CMS*_*CMS 20
我只有一个关于你的第二种方法的注释,你不应该使用一个数组来存储非数字索引(你可以在其他语言中调用一个关联数组).
你应该使用一个简单的对象.
此外,您可能希望检查what传递给write函数的参数是否作为colors对象的属性存在,并查看它是否为函数,因此您可以在不发生运行时错误的情况下调用它:
var colors = {};
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
if (typeof colors[what] == 'function') {
colors[what]();
return;
}
// not a function, default case
// ...
}
Run Code Online (Sandbox Code Playgroud)
我今天使用了这样的结构:
var chosenColor = 'red';
var colorString = {
'red': 'The color is red.',
'green': 'The color is green.',
'blue': 'The color is blue.',
}[chosenColor] || 'The color is unknown.';
Run Code Online (Sandbox Code Playgroud)
我喜欢根据选择选择字符串的代码非常少.
你也可以将它传递给一个函数:
alert({
'red': 'The color is red.',
'green': 'The color is green.',
'blue': 'The color is blue.',
}[chosenColor] || 'The color is unknown.');
Run Code Online (Sandbox Code Playgroud)