2012-03-07 76 views
0

...或者some()every()的專有名稱是什麼。基本上,我正在尋找一個功能或插件,讓我寫的東西,如:jquery布爾迭代器

okay = $("#myForm input").every(function() { 
    return $(this).val().length > 0 
}) 

hasErrors = $(listOfUsers).some(function() { 
    return this.errorCount > 0; 
}) 

你上心。

(在你嘗試過的小隊到達之前,我搜索了一下,發現jquery.arrayUtils,但那段代碼對我來說並不令人信服)。

+1

這種功能通常被稱爲[聚合函數(http://en.wikipedia.org/wiki/Aggregate_function),因爲它們返回從單一的價值列出一個值。集合函數還包括'count()','sum()'和'average()'等等。 – 2012-03-07 10:52:48

回答

3

一個簡單的,簡單的實現:

$.fn.some = function(callback) { 
    var result = false; 
    this.each(function(index, element) { 
     // if the callback returns `true` for one element 
     // the result is true and we can stop 
     if(callback.call(this, index, element)) { 
      result = true; 
      return false; 
     } 
    }); 
    return result; 
}; 

$.fn.every = function(callback) { 
    var result = true; 
    this.each(function(index, element) { 
     // if the callback returns `false` for one element 
     // the result is false and we can stop 
     if(!callback.call(this, index, element)) { 
      result = false; 
      return false; 
     } 
    }); 
    return result; 
}; 

隨着ES5,陣列已經提供了方法everysome,所以你可以達到同樣內置的方法:

okay = $("#myForm input").get().every(function(element) { 
    return $(element).val().length > 0 
}); 

但在沒有HTML5 shim的舊版IE中無法使用。

+0

的確很簡單!我希望每個回調都能得到相同的每個回調獲得的參數(即索引,對象)。任何想法如何實現這一目標? – georg 2012-03-07 11:12:22

+0

是的。我更新了代碼。將這些值提供給回調是非常有意義的(應該自己想到這一點))。 – 2012-03-07 11:17:27

+0

看起來不錯,謝謝。 – georg 2012-03-07 11:38:16

0

你可以做這樣的事情

okay = $("#myForm input").each(function() { 
    return $(this).val().length > 0 
}) 

okay = $("#myForm input").find('class').each(function() { 
    return $(this).val().length > 0 
}) 
+0

這不回答問題... – 2012-03-07 11:19:07