2017-07-26 9 views
1

我有這樣的代碼: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; 
}); 
+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find or findIndex? – mkaatman

+0

確切的重複,但是,這可能是一個更好的問題? https://stackoverflow.com/questions/33264318/can-jquerys-filter-be-used-such-that-it-stops-searching-when-the-first-element/33264354#33264354 –

回答

2

您不能擺脫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對象。

+0

@DarthJDG謝謝你,我錯過了最後的'}' –

+0

沒問題,對於鬼鬼祟祟的編輯感到抱歉。 ;) – DarthJDG