我不想在我的代码中使用Switch,所以我正在寻找一些替代方法
使用开关的示例:
function write(what) {
switch(what) {
case 'Blue':
alert ('Blue');
break;
...
case 'Red':
alert ('Red');
break;
}
}
不带开关的示例:
colors = [];
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
colors[what]();
}
我的问题是:
发布于 2010-02-22 03:43:11
我只注意到您的第二种方法,即使用shouldn't use an Array来存储非数值索引(在其他语言中,您会将其称为关联数组)。
你应该使用一个简单的对象。
此外,您可能希望检查传递给write
函数的what
参数是否作为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
// ...
}
发布于 2012-02-15 20:46:35
我今天使用了这样的结构:
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.';
我喜欢这是一个非常少量的代码来选择一个基于选择的字符串。
你也可以把它传递给一个函数:
alert({
'red': 'The color is red.',
'green': 'The color is green.',
'blue': 'The color is blue.',
}[chosenColor] || 'The color is unknown.');
发布于 2011-01-15 06:25:04
您可以使用对象字面量,并尝试catch来捕获默认值:
function write(what) {
var colors = {
'Blue': function(){ alert('Light-Blue'); },
'Red': function(){ alert('Deep-Red'); },
'Green': function(){ alert('Deep-Green'); }
}
try {colors[what]();}
catch(err) {colors['Green']();}//default behaviour
}
write('Pink');
https://stackoverflow.com/questions/2307157
复制相似问题