为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

鸿蒙传说 2022-11-27 16:04:41
我希望能够在 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(),但它们都不起作用。谢谢!
查看完整描述

2 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

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")


查看完整回答
反对 回复 2022-11-27
?
慕娘9325324

TA贡献1783条经验 获得超5个赞

一种选择是使用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 来看,您并不清楚您在寻找什么。


查看完整回答
反对 回复 2022-11-27
  • 2 回答
  • 0 关注
  • 276 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号