我不认为switch
是一个很好的选择。我认为你的“跌宕起伏”模式可以保证失败:每case
声明在第一个被触发后也会执行。
你可以使用switch
这个工作,但你不得不放弃你的“失败”,你需要遍历各个成果。
或者,如果你只是想避免任何循环,最直接的解决方案是使用一系列的非排他性if
语句,就像这样:
function whatFruitColors(fruitList) {
var results = [];
if(fruitList.indexOf('apple' ) >= 0 && results.indexOf('red' ) === -1) fruitList.push('red' );
if(fruitList.indexOf('banana' ) >= 0 && results.indexOf('yellow') === -1) fruitList.push('yellow');
if(fruitList.indexOf('kiwi' ) >= 0 && results.indexOf('green') === -1) fruitList.push('green');
if(fruitList.indexOf('mango' ) >= 0 && results.indexOf('orange') === -1) fruitList.push('orange');
if(fruitList.indexOf('orange' ) >= 0 && results.indexOf('orange') === -1) fruitList.push('orange');
if(fruitList.indexOf('pineapple') >= 0 && results.indexOf('yellow') === -1) fruitList.push('yellow');
return results;
}
whatFruitColors(['pineapple','banana','apple','mango','orange']);
这是可行的,但它是坦言原油,还有很多redudant代码。此外,保持这一点 - 即增加新的水果,保持水果+颜色组合的名单 - 将是一个痛苦的屁股。
这是一个完美用例为Array.reduce
。这里是一个更好的解决方案:
function whatFruitColors(fruitList) {
// a static lookup "table" that declares the color of every fruit
var FRUIT_COLORS = {
'apple': 'red',
'banana': 'yellow',
'kiwi': 'green',
'mango': 'orange',
'orange': 'orange',
'pineapple': 'yellow'
};
return fruitList.reduce(function(foundColors, thisFruit) {
var thisFruitColor = FRUIT_COLORS[thisFruit];
if(foundColors.indexOf(thisFruitColor) === -1) {
foundColors.push(thisFruitColor);
}
return foundColors;
}, []);
}
whatFruitColors(['pineapple','banana','apple','mango','orange']);
来源
2017-02-21 05:44:52
Tom
这对我来说是最接近OP的要求模式的精神 – Tom
*“如果你需要一个更不优雅的解决方案”* - 这是一个有趣的方式,虽然我同意这更接近于OP的想法,也许可以使用switch语句设置一个临时变量'currentColour ='red'',然后执行'.indexOf()'测试和'.push() '切换后 - 只需少一点重复。 – nnnnnn