在JavaScript中切换字符串匹配的语句 [英] Switch statement for string matching in JavaScript
问题描述
如何为以下条件编写swtich?
How do I write a swtich for the following conditional?
如果网址包含foo,则settings.base_url为 bar。
If the url contains "foo", then settings.base_url is "bar".
以下是实现所需的效果,但我觉得这在交换机中更易于管理:
The following is achieving the effect required but I've a feeling this would be more manageable in a switch:
var doc_location = document.location.href;
var url_strip = new RegExp("http:\/\/.*\/");
var base_url = url_strip.exec(doc_location)
var base_url_string = base_url[0];
//BASE URL CASES
// LOCAL
if (base_url_string.indexOf('xxx.local') > -1) {
settings = {
"base_url" : "http://xxx.local/"
};
}
// DEV
if (base_url_string.indexOf('xxx.dev.yyy.com') > -1) {
settings = {
"base_url" : "http://xxx.dev.yyy.com/xxx/"
};
}
推荐答案
你可以'在 (这不是非常正如Sean在评论中指出的那样。请参阅最后的注释。) 开关
中执行此操作,除非您正在执行完整字符串匹配;正在进行 substring 匹配。
You can't do it in a (This isn't quite true, as Sean points out in the comments. See note at the end.)switch
unless you're doing full string matching; that's doing substring matching.
如果您对顶部的正则表达式正在剥离您在比赛中不想比较的所有内容感到高兴,则不需要一个子串匹配,并且可以这样做:
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;
}
...但同样,只有在完成时才有效你匹配的字符串。如果 base_url_string
是yyy.xxx.local,那么它将会失败,而您当前的代码将匹配xxx.local分支中的代码。
...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.
更新:好的,技术上你可以使用 switch
用于子串匹配,但在大多数情况下我不推荐它。这是如何(实例):
Update: Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations. 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;
}
}
这是因为JavaScript 切换
语句工作,特别是两个关键方面:第一,这些案例以源文本顺序考虑,其次是选择器表达式(关键字 case
之后的位)是表达式评估该案例的评估(不像其他语言中的常量)。因为我们的测试表达式是 true
,第一个 case
表达式导致 true
将成为使用者。
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). So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.
这篇关于在JavaScript中切换字符串匹配的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!