You can't do it in a switch
unless you're doing full string matching;
(除非你正在进行完整的字符串匹配,否则你无法在switch
执行此操作;)
that's doing substring matching.(那是在进行子串匹配。)
(This isn't quite true, as Sean points out in the comments. See note at the end.)(( 正如肖恩在评论中指出的那样, 这并不完全正确。最后请注意。))
If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:
(如果你很高兴你的顶级正则表达式剥离了你不想在比赛中比较的所有东西,你不需要子串匹配,并且可以:)
switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
...but again, that only works if that's the complete string you're matching.
(...但是,只有当你匹配的是完整的字符串时,才有效。)
It would fail if base_url_string
were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.(如果base_url_string
是“yyy.xxx.local”,那么它将失败,而您当前的代码将匹配“xxx.local”分支中的代码。)
Update : Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations.
(更新 :好的,技术上你可以使用switch
进行子串匹配,但我不建议在大多数情况下使用它。)
Here's how ( live example ):(这是如何( 实例 ):)
function test(str) {
switch (true) {
case /xyz/.test(str):
display("? Matched 'xyz' test");
break;
case /test/.test(str):
display("? Matched 'test' test");
break;
case /ing/.test(str):
display("? Matched 'ing' test");
break;
default:
display("? Didn't match any test");
break;
}
}
That works because of the way JavaScript switch
statements work , in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case
) are expressions that are evaluated as that case is evaluated (not constants as in some other languages).
(这是因为JavaScript switch
语句的工作方式 ,特别是两个关键方面:第一,案例以源文本顺序考虑,第二,选择器表达式(关键字case
之后的位)是被评估为的表达式案例被评估(不像其他语言中的常量)。)
So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.(因此,由于我们的测试表达式为true
,因此第一个导致true
case
表达式将是使用的表达式。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…