简体   繁体   English

Javascript过滤器返回空数组

[英]Javascript filter returning empty array

I'm using the array.protoype.filter method and it is returning an 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);

Here is the console output for tagstring within the loop and for brandFiltered outside the loop: 这是循环中的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 []

This function is triggered by selecting a checkbox. 选中复选框即可触发此功能。 What this filter is meant to do is take an array of html elements, check their class attribute for the presence of a selected value, and return only the class names for the elements which meet the filter's criteria. 此过滤器的目的是获取一个html元素数组,检查其class属性是否存在所选值,并仅返回符合过滤条件的元素的类名。 The console log within the loop is showing the correct elements but for some reason an empty array is returned outside the loop. 循环中的控制台日志显示正确的元素,但由于某种原因,在循环外返回一个空数组。 Am I using the filter method incorrectly? 我是否错误地使用过滤方法?

Your return tagString; 你的return tagString; line returns a result to the $.each function, your isSelected function does not currently return anything. line将结果返回给$.each函数,您的isSelected函数当前不返回任何内容。

You can edit that function to perform a check and return true when the string is found. 您可以编辑该函数以执行检查,并在找到该字符串时返回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;
    }

Filter functions differently than something like map, it is only used to reduce the size of your array by checking against a condition and returning true or false. 过滤器的功能与map之类的不同,它仅用于通过检查条件并返回true或false来减小数组的大小。 If you want to have only an array of classes you can map after the fitler. 如果你想只有一个类数组,你可以在fitler之后映射。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM