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

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 來看,您并不清楚您在尋找什么。
添加回答
舉報