Javascript过滤器返回空数组

时间:2016-04-18 15:12:58

标签: javascript jquery

我正在使用array.protoype.filter method并返回一个空数组。

   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的控制台输出以及循环外的brandFiltered:

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属性是否存在所选值,并仅返回符合过滤条件的元素的类名。循环中的控制台日志显示正确的元素,但由于某种原因,在循环外返回一个空数组。我是否错误地使用过滤方法?

1 个答案:

答案 0 :(得分: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'); });