一个简单的,简单的实现:
$.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