一個簡單的,簡單的實現:
$.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,陣列已經提供了方法every
和some
,所以你可以達到同樣內置的方法:
okay = $("#myForm input").get().every(function(element) {
return $(element).val().length > 0
});
但在沒有HTML5 shim的舊版IE中無法使用。
這種功能通常被稱爲[聚合函數(http://en.wikipedia.org/wiki/Aggregate_function),因爲它們返回從單一的價值列出一個值。集合函數還包括'count()','sum()'和'average()'等等。 – 2012-03-07 10:52:48