2016-04-18 10 views
3

array.protoype.filter methodを使用していて、空の配列を返しています。ここ空の配列を返すJavascriptフィルタ

function isSelected(value){ 

     var tagString = $(value).attr('class'); 
     $.each($(brandDrop.selections), function(index, brand) { 
     if(tagString.indexOf(brand) >= 0) { 
      console.log(tagString); 
      return tagString; 
     } 
     }); 

    } 

    var products = []; 
    $.each($('.products li'), function(index, product){ 
     products.push(product); 
    }); 

    var brandFiltered = products.filter(isSelected); 
    console.log(brandFiltered); 

はループの外側ループ内とbrandFilteredためtagstringのコンソール出力である:

AugustaCollection,Crib,publishSK,simmons,simmons-kids,wood 
cribs:2058 BellanteCollection,Crib,publishSK,simmons-kids,wood 
cribs:2058 BelmontCollection,Crib,publishSK,simmons-kids,wood 
cribs:2082 [] 

この機能は、チェックボックスを選択することによってトリガされます。このフィルタが意味するのは、html要素の配列をとり、選択された値が存在するかどうかクラス属性をチェックし、フィルタの条件を満たす要素のクラス名のみを返すことです。ループ内のコンソールログに正しい要素が表示されていますが、何らかの理由で空の配列がループの外側に返されます。フィルターメソッドを誤って使用していますか?

+3

あなた 'isSelected'メソッドは何も返さない(' undefined') –

答えて

2

return tagString;行は、結果を$.each関数に返します。isSelected関数は現在何も返しません。

チェックを実行し、文字列が見つかったときにtrueを返すようにその関数を編集できます。

function isSelected(value){  
     var tagString = $(value).attr('class'); 
     var foundString = false; 
     $.each($(brandDrop.selections), function(index, brand) { 
     if(tagString.indexOf(brand) >= 0) { 
      console.log(tagString); 
      foundString = true; 
     } 
     }); 
     return foundString; 
    } 

フィルタはmapのように機能が異なりますが、条件をチェックしてtrueまたはfalseを返すことによって配列のサイズを縮小するためにのみ使用されます。クラスの配列しか持たない場合は、fitlerの後にマップすることができます。

brandFiltered = brandFiltered.map(function(x){ return $(x).attr('class'); }); 
+0

それはあなたの配列をフィルタリングするが、あなただけのクラスを望んでいたとき、全体の要素を返すましたか?フィルタの後にマップを作成してクラス名の配列を取得するコメントを追加しました。 – IrkenInvader

+1

ありがとうございました! –

関連する問題