2017-05-30 4 views
2
var testVar = [null, true, true, false, false]; 

//Paulpro's solution (not mine) 
switch (testVar.indexOf(true)) { 
    case 1: 
    console.log('Im in the first group!'); 
    break; 
    case 2: 
    console.log('Im in the second group!'); 
    break; 
    case 3: 
    console.log('Im in the third group!'); 
    break; 
} 

testVarは、最初のグループ(インデックス1が真)の従業員に対してこの[null、true、true、false、false、false]のような配列であり、第3のグループではない。配列のインデックス用のスイッチケース

+3

switch(employee.groups [1])case true: – yBrodsky

+2

ありがとうございます!私もemployee.groups [2] employee.groups [3]などが必要です。 –

+0

データ例を表示してください。 –

答えて

3

indexOfを使用して)グループ配列のtrueの位置を見つけ、あなたのswitch文のためにそれを使用します。

contacts.forEach(function(employee, index){ 
    switch (employee.groups.indexOf(true)) { 
    case 1: 
     console.log('Im in the first group!'); 
     break; 
    case 2: 
     console.log('Im in the second group!'); 
     break; 
    } 
}); 

ユーザーが複数のグループにすることができた場合、それはif文のシリーズを使用することをお勧めします:

contacts.forEach(function(employee, index){ 
    if (employee.groups[1]) { 
     console.log('Im in the first group!'); 
    } 

    if (employee.groups[2]) { 
     console.log('Im in the second group!'); 
    } 
}); 
+0

これは、 'break;'を削除すると機能します。 1つ以上のグループについて、例えば、 var testVar = [null、true、true、false、false]; –

+0

@TylerLこれは彼らがいる最初のグループでのみ動作します。あなたの質問を読んだとき、ユーザーは1つのグループにしかいられないと思っていました。 'break'を削除すると正しく動作しません。あなたは 'case 3:'があればそれを見るでしょう。それは、あなたが実際に入っている最初のものの後に、すべてのグループに入っていると言うでしょう。 – Paulpro

+0

あなたは正しいです。クラップ元の質問を更新しています。 –

関連する問題