可替代“开关".陈述 [英] Alternative to the "switch" Statement

查看:60
本文介绍了可替代“开关".陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想在代码中使用Switch,所以我正在寻找其他选择

I do not want to use Switch in my code, so I'm looking for some alternative

带有开关的示例:

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]();

}

我的问题是:

  1. 您还有其他选择吗?
  2. 这是最好的解决方案吗?

推荐答案

我只有关于您的第二种方法的注释,您

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.

此外,您可能想检查传递给write函数的what参数是否作为colors对象的属性存在,并查看它是否是一个函数,因此您可以在没有运行时的情况下调用它错误:

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:

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
  // ...
}

这篇关于可替代“开关".陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆