我如何为以下条件写一个开关?

如果url包含“foo”,则设置。Base_url是"bar"。

以下是实现所需的效果,但我有一种感觉,这将更易于管理的开关:

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/"
    };
}

当前回答

使用位置即可。主机属性

switch (location.host) {
    case "xxx.local":
        settings = ...
        break;
    case "xxx.dev.yyy.com":
        settings = ...
        break;
}

其他回答

RegExp也可以用match方法用于输入字符串。

为了确保在case子句中有匹配,我们将根据成功匹配的输入属性测试原始str值(提供给switch语句的值)。

Input是正则表达式的静态属性,包含原始输入字符串。

当匹配失败时,它返回null。为了避免异常错误,我们在访问输入属性之前使用可选的链接操作符(或传统ES中的逻辑||条件操作符)。

const str = 'XYZ test';

switch (str) {
  case str.match(/^xyz/)?.input:
    console.log("Matched a string that starts with 'xyz'");
    break;
  case str.match(/test/)?.input:
    console.log("Matched the 'test' substring");        
    break;
  default:
    console.log("Didn't match");
    break;
}

另一种方法是使用String()构造函数将结果数组转换为字符串,该数组必须只有一个元素(没有捕获组),并且必须使用量词(.*)捕获整个字符串。在失败的情况下,null对象将成为一个'null'字符串。这似乎不太方便。

const str = 'XYZ test';

switch (str.toLowerCase()) {
  case String(str.match(/^xyz.*/i)):
    console.log("Matched a string without case sensitivity");
    break;
  case String(str.match(/.*tes.*/)):
    console.log("Matched a string using a substring 'tes'");
    break;
}

不管怎样,一个更优雅的解决方案是使用test方法而不是match,即/^find-this-in/.test(str)与switch (true),它只是返回一个布尔值,并且更容易匹配,不区分大小写。

const str = 'haystack';

switch (true) {
  case /^hay.*/i.test(str):
    console.log("Matched a string that starts with 'hay'");
    break;
}

然而,在这种情况下使用if else else if语句也是可读的

独立版本,增加工作安全性:

switch((s.match(r)||[null])[0])

function identifyCountry(hostname,only_gov=false){ const exceptionRe = /^(?:uk|ac|eu)$/ ; //https://en.wikipedia.org/wiki/Country_code_top-level_domain#ASCII_ccTLDs_not_in_ISO_3166-1 const h = hostname.split('.'); const len = h.length; const tld = h[len-1]; const sld = len >= 2 ? h[len-2] : null; if( tld.length == 2 ) { if( only_gov && sld != 'gov' ) return null; switch( ( tld.match(exceptionRe) || [null] )[0] ) { case 'uk': //Britain owns+uses this one return 'gb'; case 'ac': //Ascension Island is part of the British Overseas territory //"Saint Helena, Ascension and Tristan da Cunha" return 'sh'; case null: //2-letter TLD *not* in the exception list; //it's a valid ccTLD corresponding to its country return tld; default: //2-letter TLD *in* the exception list (e.g.: .eu); //it's not a valid ccTLD and we don't know the country return null; } } else if( tld == 'gov' ) { //AMERICAAA return 'us'; } else { return null; } } <p>Click the following domains:</p> <ul onclick="console.log(`${identifyCountry(event.target.textContent)} <= ${event.target.textContent}`);"> <li>example.com</li> <li>example.co.uk</li> <li>example.eu</li> <li>example.ca</li> <li>example.ac</li> <li>example.gov</li> </ul>

说实话,你可以做一些

function switchableMatch(s,r){
    //returns the FIRST match of r on s; otherwise, null
    const m = s.match(r);
    if(m) return m[0];
    else return null;
}

然后切换(switchableMatch(s,r)){…}

你也可以像这样使用默认的情况:

    switch (name) {
        case 't':
            return filter.getType();
        case 'c':
            return (filter.getCategory());
        default:
            if (name.startsWith('f-')) {
                return filter.getFeatures({type: name})
            }
    }

如果需要使用正则表达式,请为开关情况创建一个带有正则表达式和条件响应的对象

let test = (str) => {
    let obj = {
        'foo':'bar',
        '\/albums?':'photo'
    };
    for(let prop in obj){
        if(new RegExp(prop).test(str))return obj[prop]
    };
};

switch(test(location.href)){
    case 'bar':
        console.log('url has bar')
    break;
}

使用位置即可。主机属性

switch (location.host) {
    case "xxx.local":
        settings = ...
        break;
    case "xxx.dev.yyy.com":
        settings = ...
        break;
}