2012-08-27 35 views
0

想象我有一個數組如何檢查數組中的剩餘項目?

arr = ["one", "two", "three"] 

和邏輯

if "one" in arr 
    processOne() 

if "two" in arr 
processTwo() 

if <<there is another items in array>> 
    processOthers() 

我應該在去年if寫什麼條件? 我發現了_.difference函數,但我不想一次寫多個元素(「one」,「two」...)。

編輯

  1. if else if else不適合,因爲我需要調用0..N處理功能。
  2. 這裏是數組的例子。但是,這個代碼如果會成爲對象呢?
  3. 陣列不具有重複
+0

檢查長度和使用else會怎麼樣? –

+0

'for..in'適用於數組和對象 – timidboy

回答

3

通過使用.indexOf方法。

var index; 
if ((index = arr.indexOf('one')) !== -1) { 
    processOne(); 
    arr.splice(index, 1); 
} 

if ((index = arr.indexOf('two')) !== -1) { 
    processTwo(); 
    arr.splice(index, 1); 
} 

if (arr.length > 0) { 
    processOthers(); 
} 

更新:或者你可以循環數組。

var one = false, two = false, others = false; 
for (var i = 0; i < arr.length; i++) { 
    if (arr[i] === 'one' && !one) { 
    processOne(); 
    one = true; 
    } else if (arr[i] === 'two' && !two) { 
    processTwo(); 
    two = true; 
    } else (!others) { 
    processOthers(); 
    others = true; 
    } 
    if (one && two && others) break; 
} 
+0

我知道如何檢查元素existense。我想檢查數組中是否還有其他項目。 –

+0

@PlasticRabbit檢查我編輯的答案。如果你不想改變'arr'本身,那麼複製它。 – xdazz

+0

我想過拼接功能。它是正確的。但我覺得它聞起來。有另一種方法嗎? –

0

你應該這樣做,而不是:

如果您有:

arr = ["one", "two", "three"] 

然後:

if (something corresponds to arr[one]) 
{ 
    processOne() 
} 

elseif (something corresponds to arr[two]) 
{ 
    processTwo() 
} 

else (something corresponds to arr[three]) 
{ 
    processOthers() 
} 

應該這樣做。

+0

if else if else is not suitable。 –

相關問題