猿问

你能在 JavaScript 的 switch case 中使用函数吗

我希望能够在 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

}

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


鸿蒙传说
浏览 277回答 2
2回答

呼啦一阵风

JavaScript 中的 Switch 语句不支持模式匹配,它们只做简单的相等性检查(将 gets 的结果与[if that function would exist]lowerCase()的返回值进行比较)。startsWith(...)你可以做这样的事情:switch(true) {  case message.toLowerCase().startsWith("pay"): // if this is true, the case matches    console.log(message);    break; }您还可以编写一些帮助程序来实现更灵活的模式匹配:  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")

慕娘9325324

一种选择是使用switch(true)。var m = message.toLowerCase()switch(true) {    case m.startsWith("pay"):        console.log(message)        break}阅读原始线程以获取更多详细信息(例如,case返回值必须为 true true,例如1将不起作用(但适用于if-else.还可以考虑使用 ordinary if-else,有时它可能比switch(尤其是这个“非标准” swith(true))更具可读性和可维护性还可以考虑使用正则表达式。从 OP 来看,您并不清楚您在寻找什么。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答