簡體   English   中英

Javascript過濾器返回空數組

[英]Javascript filter returning empty array

我正在使用array.protoype.filter方法 ,它返回一個空數組。

   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);

這是循環中的tagstring和loopFiltered循環外的控制台輸出:

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元素數組,檢查其class屬性是否存在所選值,並僅返回符合過濾條件的元素的類名。 循環中的控制台日志顯示正確的元素,但由於某種原因,在循環外返回一個空數組。 我是否錯誤地使用過濾方法?

你的return tagString; line將結果返回給$.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'); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM