【问题标题】:Functional switch statement in JavascriptJavascript 中的函数式 switch 语句
【发布时间】:2017-06-05 12:53:24
【问题描述】:

假设我有一个 switch 语句,它接受一个介于 1 和某个更大值之间的变量 myData,即 300。

根据“状态码”变量,结果是另一个变量的文本值。例如,如果myData == 1,我想返回一个名为code1 的变量。如果myData == 300,我想返回一个名为code300 的变量。 Code1 和 code300 变量存储不相关的字符串,即“This is a summary”或“This is a note”。下面是一些伪代码:

var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;          
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}

我怎样才能让它工作?

【问题讨论】:

  • codeX 变量是原样吗,还是可以将它们移动到以代码为关键的对象中?
  • 它们是原样的,预定义的。
  • 你要求的是变量变量,它在 Javascript 中不起作用。理智的事情是有一个从键到值的数组或对象映射,所以你可以做一个简单的codes[myData]
  • 你完全可以拥有可变变量——使用window[variableName](数组语法)。
  • @Feathercrown 假设所有必需的 code 变量都是全局变量

标签: javascript switch-statement


【解决方案1】:

您需要为此使用查找图,而不是多个变量:

var codes = {
    1: "This is a summary",
    300: "This is a note"
};

你可以这样做

if (statusCode in codes) {
    scriptletResult = codes[statusCode];
} else {
    scriptletResult = codes[1];
}

【讨论】:

  • 这是最好的解决方案,但我相信 OP 说他由于某种原因无法移动变量。
  • 据我所知,这是最接近我想要完成的。这并没有改变有人必须编写 300 个“代码”字符串的事实,但它确实减少了所需的 switch 语句的数量......
  • @Scott 在这种情况下,var codes = {1: code1, 300: code300} 可能是一个解决方案。或者 eval 在最坏的情况下使用变量名的白名单 (-regex)。
【解决方案2】:
var myData=300;
var code1="This is a summary";
var code300=" this is a note";
var result=(function(){
switch(myData) {
case 1:
    return code1;        
case 300:
   return code300,
default:
    return "not defined";
}
})();

alert(result);

IIFE + 开关组合的完美用例。

最好的办法是:

alert([code1,code2][myData]);

【讨论】:

  • ['This is a summary', ...][myData] || 'not defined'...
  • @deceze 他想要一个功能性开关语句。不是说这有用...
  • 无论“功能开关语句”是什么意思……:P
【解决方案3】:

@Bergi 的回答是最好的方法,但如果您无法更改代码消息组合的存储方式,并且变量是全局变量,您可以使用:

scriptletResult=window["code"+myData];

【讨论】:

    【解决方案4】:
    var yourStatusCode = 300; //function get300();
    var data = "MyData"; //function data();
    
    function runner(){
        switch(data){
            case "MyData":
            myFunc();
            return "hola data we are looking for!";
            break;
            case "DataNumberTwo":
            return "this is data number 2";
            break;
            default:
            return "WOAH what data is this??";
            break;
        }
    
    }
    
    console.log(runner());
    

    【讨论】:

      【解决方案5】:

      允许 lambda 模式匹配的 JavaScript 函数式 switch 语句

      const switchF = (c, options, def) => {
        const choice = options.find(([key, ]) => {
          if (Array.isArray(key)) {
            return key.indexOf(c) >= 0;
          }
          if (typeof key === "function") {
            return key(c);
          }
          return key === c;
        });
        if (!choice) return def();
        const [, choiceVal] = choice;
        if (typeof choiceVal === "function") return choiceVal();
        if (typeof choiceVal === "string") {
          return switchF(choiceVal, options, def);
        }
        throw Error("switch F Failed!");
      };
      

      使用示例:

      
      const switcher = (c) =>
        switchF(
          c,
          [
            ["foo", () => "Foo option"],
            ["bar", "foo"],
            [(v) => v > 3, () => 99],
          ],
          () => "DEFAULT"
        );
      
      console.log(switcher("foo")); // returns 'Foo'
      console.log(switcher("bar")); // returns 'Foo
      console.log(switcher(4)); // returns '99'
      console.log(switcher(2)); // returns 'DEFAULT'
      console.log(switcher("zzz")); returns 'DEFAULT'
      
      

      【讨论】:

        猜你喜欢
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-19
        • 2023-03-15
        • 2019-12-30
        • 1970-01-01
        相关资源
        最近更新 更多