javascript - jQuery.filter() : exit before the end

标签 javascript jquery filter

我有这个代码:

var image_match = $('#my_id image').filter(function(i, el) {
    return  el.attributes.x.value == x_image;
});

$('#my_id image') 给出了一个很长的数组(几千个)但幸运的是我知道有多少元素会通过测试(通常只有一个)所以我可以停止“循环” ' 一旦找到元素。问题是我不知道该怎么做(或者如果可能的话)。

这是为了提高效率,所以我正在寻找一个高效的解决方案。

也许是这样的,但是它有效率吗?

var target_number=3;//or whatever
var image_match = $('#my_id image').filter(function(i, el) {
    var counter=0;
    if (el.attributes.x.value == x_image) {
        counter+=1;
    };
    if (counter==target_number) {
        return  el.attributes.x.value == x_image;
        break;//return (false);//exit
    }
    return  el.attributes.x.value == x_image;
});

最佳答案

您不能跳出 filter() 循环,因为它旨在将其逻辑应用于所有元素。

如果您想提前退出循环,我建议您更改逻辑以使用 each()。然后你可以return false;退出循环:

var target_number = 3, matches = [];

$('#my_id image').each(function(i, el) {
  if (el.attributes.x.value == x) {
    matches.push($(this));

    if (matches.length == target_number)
      return false;
  }
});

matches 现在将大致等同于您的 image_match 变量的内容,只是它将是一个数组而不是 jQuery 对象。

或者,您可以使用 map() 直接构建一个仅包含所需值的数组:

let matches = $('#my_id image').map((i, el) => el.attributes.x.value === x ? $(el) : null).get();

关于javascript - jQuery.filter() : exit before the end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330997/

相关文章:

javascript - 错误 : Could not load module in dojo

javascript - 数据表上的范围日期搜索 (CodeIgniter)

javascript - 优化:使用ajax加载内容

javascript - 修改一个简单的jquery游戏

javascript - Ajax get 方法不起作用

php - CSS3 Webkit-filter 属性

javascript - 视差下一个和上一个导航

javascript - Backbone : restore focus after rendering

Python NumPy 将 FFT 转换为文件

javascript - 用于嵌套 ng-repeat 的 Angular 独特过滤器