jQuery .filter():在结束之前退出

fab*_*bio 4 javascript jquery filter

我有以下代码:

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

$('#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;
});
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

您无法打破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;
  }
});
Run Code Online (Sandbox Code Playgroud)

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