2014-07-19 38 views
10

這是我想要做的只是一個簡單的例子:是否可以在switch語句中使用.contains()?

switch (window.location.href.contains('')) { 
    case "google": 
     searchWithGoogle(); 
     break; 
    case "yahoo": 
     searchWithYahoo(); 
     break; 
    default: 
     console.log("no search engine found"); 
} 

如果這是不可能/不可行這將是一個更好的選擇?

解決方案:

閱讀一些的答覆後,我發現下面是一個簡單的解決方案。 「

function winLocation(term) { 
    return window.location.href.contains(term); 
} 
switch (true) { 
    case winLocation("google"): 
     searchWithGoogle(); 
     break; 
    case winLocation("yahoo"): 
     searchWithYahoo(); 
     break; 
    default: 
     console.log("no search engine found"); 
} 
+0

你試過使用正則表達式嗎? –

+0

不需要。它必須是'switch(true){case location.href.contains(「google」)...'這簡直是愚蠢的 – mplungjan

+0

是的,但它不會達到您的期望。用於開關的表達式被評估*一次* - 在這種情況下,結果是真/假,而不是字符串。 – user2864740

回答

7

」是「,但它不會達到您的預期。

用於開關的表達式進行求值一次 - 在這種情況下contains評估爲真/假值作爲結果(例如switch(true)switch(false)) ,不能夠在一個殼體相匹配的字符串。

因此,上述方法將不起作用。除非這種模式比較大/可擴展,否則只需使用簡單的if/else-if語句。

var loc = .. 
if (loc.contains("google")) { 
    .. 
} else if (loc.contains("yahoo")) { 
    .. 
} else { 
    .. 
} 

然而,考慮是否有是返回「Google」或「雅虎」一classify功能等,或許使用上述條件語句。然後可以這樣使用它,但在這種情況下可能會過度使用。

switch (classify(loc)) { 
    case "google": .. 
    case "yahoo": .. 
    .. 
} 

雖然上述討論在JavaScript和Ruby和Scala(以及可能其它)這樣的機制來處理一些更「高級開關」的使用。

+0

謝謝你的回答。它幫助我找到一個解決方案,我更新了包含的主要答案。 – RayB

+0

@ Rayz321是的,這也是一種可能的形式 - 但這不是我的偏好/建議。 – user2864740

相關問題