如何在javascript中管理100的else if语句?更好的方法?

wai*_*ler 2 javascript

我正在学习javascript.我想回答我的测验 - 分类网址.如何改进我对100个网址进行分类的答案..我的答案不是那么有效......任何帮助?谢谢.

var pageURL = document.location.href;
var isHealth = pageURL.indexOf("http://www.domain.com/health/");
var isCar = pageURL.indexOf("http://www.domain.com/car/");
var isFuel = pageURL.indexOf("http://www.domain.com/fuel/");
var isRoadside = pageURL.indexOf("http://www.domain.com/roadside/");

if (isHealth > -1) {
return 'health';
} else if (isCar > -1) {
return 'car';
} else if (isRoadside > -1) {
return 'roadside';
} else if (isFuel > -1) {
return 'fuel';
} else return 'other';
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 6

您可以使用map对象和for循环来检查哪个url与当前页面匹配:

var urls = {
    health: "http://www.domain.com/health/",
    car: "http://www.domain.com/car/",
    roadside: "http://www.domain.com/fuel/",
    fuel: "http://www.domain.com/roadside/"
};

var pageURL = document.location.href;

for (var key in urls) {
    if (pageUrl.indexOf(urls[key]) > -1) {
        return key;
    }
}
return "other";
Run Code Online (Sandbox Code Playgroud)