2016-10-30 57 views
0

我希望檢查event中的所有值都包含在state中。是這樣的函數應該返回true,否則爲false。這樣做的好方法是什麼?確保陣列中的所有值都在另一個陣列中

const state = [1,2,4,5,6,7] 
const event = [1,2] 
if(state.contains(event))(} 
+0

重複http://stackoverflow.com/q/16312528/218196 –

回答

3

您可以使用every()includes()陣列方法:

const state = [1, 2, 4, 5, 6, 7]; 
 
const event = [1, 2]; 
 
console.log(event.every(x => state.includes(x)));

-2

確定是否一個事件包含的數據不存儲在狀態:

 let state = [1,2,3,5,6,7,8,9]; 
 
     
 
     let event = [1,2,3]; 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     event = [] 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     event = [4] 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     event = [1,2,4] 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     state = []; 
 

 
     event = [1,2,3]; 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     event = [] 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     event = [4] 
 
     console.log(event.some(a=>!state.includes(a))); 
 

 
     event = [1,2,4] 
 
     console.log(event.some(a=>!state.includes(a)));

+0

如果您有任何問題,最好將它留作評論,或手動測試代碼,以便您知道它是正確的,不得不問。此代碼不起作用,因爲在這種情況下'find'不是正確的功能。 – loganfsmyth

+0

@loganfsmyth更新我的回答 – Baz

+0

將你的代碼與@ Gothdo的答案進行比較,你會發現你仍然返回錯誤的值。如果包含所有內容,則您要求「true」,如果不包含某些內容,則此答案爲「true」。 – loganfsmyth

相關問題