与窗口位置href作为我的案件switch switch case statment

与窗口位置href作为我的案件switch switch case statment

问题描述:

我正在寻找使用开关case语句为我在地点href的不同条件。我想,以避免继续写作的if语句与窗口位置href作为我的案件switch switch case statment

if (/red/.test(self.location.href)){ 
    //do this red 
} 

if (/blue/.test(self.location.href)){ 
    //do this blue 
} 

if (/yello/.test(self.location.href)){ 
    //do this yellow 
} 
+0

取决于该URL的其余部分,但你可以做这样的事情'VAR URL =“http://yoursite.com/red”; var color = url.replace('http://yoursite.com/','');'然后打开颜色。基本的想法是设置一个基础url,然后从当前url中删除基础url – kennypu 2013-02-26 02:04:44

+0

你能解释你的* exact *问题吗? – Blender 2013-02-26 02:10:47

var _url = window.location.href; 
swith(true){ 
    case /red/.test(_url): 
    //do red 
    break; 
    case /blue/.test(_url): 
    //do blue 
    break; 
    case /yellow/.test(_url): 
     // do yellow 
    break; 
} 
+1

我只想用一个'if'块。 – Blender 2013-02-26 02:05:27

+1

谢谢詹姆斯。如果条件陈述更清洁,你认为有20个吗? – user992731 2013-02-26 02:08:21

+0

顺便说一句 - 如果你接受我的答案,请'检查'!大声笑..试图起床我的代表:-)。关于你的问题,有几个jsperf测试和“if”陈述在性能方面似乎取胜。对于较小的分组,我个人喜欢切换语句。但是我认为对于像20这样的东西,如果/否则如果你期望高流量,如果可能会给你更大的回报。 – 2013-02-26 02:10:59