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条经验 获得超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 来看,您并不清楚您在寻找什么。
添加回答
举报