您可以在 JavaScript 中的 switch case 中使用函数吗

Lev*_*_OP 2 javascript node.js

我希望能够在 switch case 语句上调用函数,但我似乎无法弄清楚。例子:

switch(message.toLowerCase()) {
    // the startsWith would be an extension of the message.toLowerCase()
    // so that the case would be checking for message.toLowerCase().startsWith("pay")
    case startsWith("pay"):
        console.log(message)
        break
}
Run Code Online (Sandbox Code Playgroud)

我尝试过使用 case.function()、function(case) 和 case function(),但它们都不起作用。谢谢!

Jon*_*lms 6

JavaScript 中的 Switch 语句不支持模式匹配,它们仅执行简单的相等性检查(将lowerCase()gets 的结果与 [if that function would exist] 的返回值进行比较startsWith(...))。不过你可以这样做:

switch(true) {
  case message.toLowerCase().startsWith("pay"): // if this is true, the case matches
    console.log(message);
    break;
 }
Run Code Online (Sandbox Code Playgroud)

您还可以编写一些帮助程序来实现更灵活的模式匹配:

  const match = (...patterns) => value=> patterns.find(p => p.match(value))(value);
   const pattern = match => fn => Object.assign(fn, { match });
  const startWith = a => pattern(v => v.startsWith(a));

 match(
    startsWith("b")(console.error),
    startsWith("a")(console.log),
    startsWith("a")(console.error)
 )("abc")
Run Code Online (Sandbox Code Playgroud)

  • “if-else”有什么问题? (2认同)