亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

你能在 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條經驗 獲得超4個贊

一種選擇是使用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 關注
  • 266 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號