首页 > 解决方案 > 如何将此 else if 语句转换为 switch 语句?

问题描述

我创建了一个函数来每秒检查网站的当前 url 并根据某个值字符串更改 HTML 元素中的元标记图像。我的代码很完美,但是我想让我的代码更具可读性 7 优化......所以我想把这段代码变成 switch 语句,但我现在无法自己弄清楚。任何帮助将不胜感激。这是代码:

// Variable declarations
var imgOgSrc = $('meta[property="og:image"]');
var twitterImgSrc = $('meta[name="twitter:image:src"]');
var currentUrl;

// Checks for current url & changes meta tags depending on slug value
function getCurrentUrl(){
    currentUrl = window.location.href;

    if(currentUrl.toLowerCase().indexOf('python') >= 0) {
            imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
            twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    }   else if (currentUrl.toLowerCase().indexOf('java') >= 0) {
            imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
            twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    }   else if (currentUrl.toLowerCase().indexOf('php') >= 0) {
            imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
            twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    }
        else {
            imgOgSrc.attr('content', currentUrl);
            twitterImgSrc.attr('content', currentUrl);
    }
}   

标签: javascriptjqueryswitch-statement

解决方案


python您可以为,javaphpwithimgOgSrctwitterImgSrcproperties取一个对象,并null为不匹配的 URL 使用一个属性。

function getTarget(url) {
    const targets = { 
        python: {
            imgOgSrc: 'data1',
            twitterImgSrc: 'data2'
        },
        java: {
            imgOgSrc: 'data3',
            twitterImgSrc: 'data4'
        },
        php: {
            imgOgSrc: 'data5',
            twitterImgSrc: 'data6'
        },
        null: {                    // default values
            imgOgSrc: 'data7',
            twitterImgSrc: 'data8'
        }
    };
    return targets[url.toLowerCase().match(new RegExp(Object.keys(targets).join('|')))];
}

console.log(getTarget('blablajavabla'));
console.log(getTarget('blablabla'));


推荐阅读