简体   繁体   English

替代“switch”语句

[英]Alternative to the "switch" Statement

I do not want to use Switch in my code, so I'm looking for some alternative我不想在我的代码中使用 Switch,所以我正在寻找一些替代方案

Example with Switch:开关示例:

function write(what) {

  switch(what) {

    case 'Blue':
      alert ('Blue');
    break;

    ...

    case 'Red':
      alert ('Red');
    break;

  }

}

Example without Switch:没有开关的例子:

colors = [];

colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };


function write(what) {

  colors[what]();

}

My questions are:我的问题是:

  1. Do you know any other alternatives?你知道其他的选择吗?
  2. Is this best solution?这是最好的解决方案吗?

I have only a note about your second approach, you shouldn't use an Array to store non-numeric indexes (that you would call in other languages an associative array ). 我只有一个关于你的第二种方法的注释,你不应该使用一个数组来存储非数字索引(你可以在其他语言中调用一个关联数组 )。

You should use a simple Object. 你应该使用一个简单的对象。

Also, you might want to check if the what argument passed to your write function exists as a property of your colors object and see if it's a function, so you can invoke it without having run-time errors: 此外,您可能想要检查传递给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
  // ...
}

I used a structure like this today: 我今天使用了这样的结构:

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.';

I like that it's a really small amount of code to choose a string based on choice. 我喜欢根据选择选择字符串的代码非常少。

You could also pass it to a function: 你也可以将它传递给一个函数:

alert({
    'red': 'The color is red.',
    'green': 'The color is green.',
    'blue': 'The color is blue.',
}[chosenColor] || 'The color is unknown.');

You could use object literals, and try catch to trap the default: 您可以使用对象文字,并尝试使用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');

Question 2: 问题2:

Generally, if you can replace custom control structures with a dictionary lookup, you're perfectly fine. 通常,如果您可以使用字典查找替换自定义控件结构,那么您就完全没问题了。 It's easy to read and highly elegant -- stick with it. 它易于阅读和高雅 - 坚持下去。

I had to do do a compare for a group sort of object props for a list and did not want to do a switch/case for all the possibilities so I did an array of objects assignment to a numeric rank first so the case became a simple compare. 我必须做一个列表的一组对象道具的比较,并且不想为所有可能性做一个开关/案例,所以我做了一个对象数组,首先分配给一个数字等级,所以案例变得简单相比。 This is only 4 possibilities but you get the drift of how to extend this to situation where a switch/case becomes unmanageable: 这只有4种可能性,但是如何将这种情况扩展到开关/外壳变得无法管理的情况:

function mySort2(item1,item2){ function mySort2(item1,item2){

     var matrix = {  
    'repair': 4,  
    'r/r': 3,  
    'part': 2,  
    'misc': 1  
  };  

(matrix[item1.category] < matrix[item2.category]) ? return +1 : return -1;

// if possible bad data need to check for this first ??? //如果可能的坏数据需要先检查一下???

i1=matrix[item1.category] || null;
i2=matrix[item2.category] || null;

if (i1==null){
    // handle bad data in item 1
    return +1; // put it after 2
}

if (i2==null){
    // ditto 
    return -1; //put 1 first
}

if (i1<i2) 
    return +1;
else 
    return -1;

} }

An alternative is to define a class with a write method, and override that in subclasses Red and Blue to do the right thing. 另一种方法是使用write方法定义一个类,并在子类RedBlue重写它以做正确的事情。

Whether or not that is better than your proposed solution, depends on your particular situation. 这是否比您提出的解决方案更好,取决于您的具体情况。

You are pretty much there already. 你已经在那里了。 If possible you might want to add a helper function to make the setup easier. 如果可能,您可能需要添加辅助函数以使设置更容易。 For Example: 例如:

function setup(what)
{
    colors[what] = function() { alert(what); };
}

EDIT: 编辑:
If what you want to do for each option is more complicated clearly this will not work. 如果您想为每个选项做的事情更复杂,那么这将无效。 As mentioned in the comments by @roe this uses the global colors which is often frowned upon. 正如@roe的评论中所提到的,这使用了经常不赞成的全局颜色。

As I said, it's great. 正如我所说,这很棒。 The only thing I can add to your solution is that it's perhaps better to localize your colors . 我可以添加到您的解决方案中的唯一方法是,本地化您的colors可能更好。

function write(what) {
    var colors = [];
    colors['Blue'] = function() { alert('Blue'); };
    colors['Red'] = function() { alert('Red'); };
    colors[what]();
}

Alternatively, you can also use Dictionaries, so you could see the type of the function return, I think it's clean and scalable, although it's just pure JS.或者,您也可以使用 Dictionaries,这样您就可以看到函数返回的类型,我认为它是干净且可扩展的,尽管它只是纯 JS。

const ColorDictionary = {
  red: 'applies red color',
  blue: ' applies blue color',
  green: 'applies green color',
}

const useShowColors = (color) => {

 // color will be selected or fallout to default value.
 const getColor = () => (
  ColorDicionary[color] ?? 'applies default color' 
 )
 
 return { getColor }
}

const { getColor } = useShowColors() //pass the color you wish.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM