2016-11-27 20 views
-1

我有一個開關語句,並且對於每種情況都有一個這種情況的負載情況。檢查開關櫃內的大量情況

這是我到目前爲止。

exports.message = function message(message) { 
    switch (message.toLowerCase()) { 
    case "un": 
    case "one": 
    case "uno": 
    case "um": 
    case "unus": 
    case "ano": 
    case "un": 
    //100 + other cases... 
     return "Returned msg here" 
    break; 

    default: return "Sorry, I didn't quite understand that." 

    } 
} 

在互聯網上尋找答案後,我找到了所有我能找到的答案,但這不適合我。

由於我的一些案件有多達200個不同的「案件」,我正在尋找另一種方式。因爲這樣做不僅醜陋,長(200行只是一個案例),但如果我想改變任何東西,也很難操縱。

我會像最好是這樣的:

exports.message = function message(message) { 
    switch (message.toLowerCase()) { 
    case ["un", "one", "uno", "um", "unus", "ano", "un", /* 100+ other cases...*/] 
     return "Returned msg here" 
    break; 

    default: return "Sorry, I didn't quite understand that." 

    } 
} 

什麼是做到這一點的最好方法是什麼?

謝謝!

+0

開關塊不適用於大量可能的值。只需使用容器對象(如Array)並測試值是否存在。 – faintsignal

回答

0

你可以使用一個哈希表,像

{ 
    un: true, 
    one: true, 
    uno: true, 
    // ... 
} 

if (hash[message.toLowerCase()]) { // ... 

或數組訪問,就像

[ 
    "un", "one", "uno", "um", "unus", "ano", "un" 
] 

訪問與

if (array.indexOf(message.toLowerCase()) !== -1) { // ... 
0

我建議把每個case的話到陣列的對象,並使用Array.indexOf(caseWord) > -1,看看這個詞出現在阿雷,是這樣的:

var equivalentWordsFor = { 
     'one' : ["un", "one", "uno", "um", "unus", "ano", "un"] 
} 

if (equivalentWordsFor.one.indexOf(message) > -1) { 
    return "Returned message here."; 
} 

Array.prototype.indexOf()回報提供的字符串的索引在被調用的數組內;因爲這可以包括0(JavaScript數組的第一個元素的索引),包含零的任何正數表示找到的匹配,而-1表示未找到提供的字符串。

也將是可能使用Array.prototype.some()

var equivalentWordsFor = { 
     'one' : ["un", "one", "uno", "um", "unus", "ano", "un"] 
} 

if (equivalentWordsFor.one.some(

    // 'word' is a reference to the current Array-element of the 
    // Array over which we're iterating. 

    // if 'word' is precisely equal to 'msg' the result is 
    // of course 'true' and 'false' if not; if any element 
    // satisfies this assessment Array.prototype.some() returns 
    // true to the calling context, otherwise - if no element 
    // satisfies the assessment - the method returns false: 
    word => word === msg 
)) { 
    return "Returned message here."; 
} 

Array.prototype.some()如果所提供的參數返回true在陣列的任何元件,並false如果沒有發現匹配提供的參數元素返回一個布爾true

很明顯,這兩種方法都需要另外一個「兩個」字等價的數組,但它應該比使用switch() {...}的等效方法更易於維護。

參考文獻:

+0

我的歉意,amplungjan,看着時間戳,似乎我們每個人都在同一分鐘內寫下我們的答案。此外,憑藉世界上最好的意志,這是最明顯的向後兼容解決方案。如果你願意,我很高興能夠刪除答案的組成部分,而不是專注於'Array.prototype.some()'? –

0

你可以做到這一點通過以下方式:

var msg = message.toLowerCase() 
if (~["un", "one", "uno", "um", "unus", "ano", "un", ...].indexOf(msg)) { 
    // do something 
} else if (~["deux", "two", "dos", ...].indexOf(msg)) { 
    // do something else 
} ... 

請注意,如果你有一個性能瓶頸,你會希望把最頻繁的情況下,在開始。

您可能還想先從列表中刪除重複項目以獲得更好的性能(發送的項目包含「un」兩次)。

array.indexOf(item)返回item的索引array-1(如果未找到)。

~x相當於-x-1。當且僅當x != -1它將返回true