不知道为什么每一个()不为你工作:
BROKEN - 见下FIX
function check(arr, closure)
{
$.each(arr,function(idx, val){
// Note, two options are presented below. You only need one.
// Return idx instead of val (in either case) if you want the index
// instead of the value.
// option 1. Just check it inline.
if (val['Foo'] == 'Bar') return val;
// option 2. Run the closure:
if (closure(val)) return val;
});
return -1;
}
的作品评论其他例子。
Array.prototype.UContains = function(closure)
{
var i, pLen = this.length;
for (i = 0; i < pLen; i++)
{
if (closure(this[i])) { return i; }
}
return -1;
}
// usage:
// var closure = function(itm) { return itm.Foo == 'bar'; };
// var index = [{'Foo':'Bar'}].UContains(closure);
好吧,我的第一个例子是HORKED。大约6个月后,指出了我和多个upvotes。 :)
正常,则检查()应该是这样的:
function check(arr, closure)
{
var retVal = false; // Set up return value.
$.each(arr,function(idx, val){
// Note, two options are presented below. You only need one.
// Return idx instead of val (in either case) if you want the index
// instead of the value.
// option 1. Just check it inline.
if (val['Foo'] == 'Bar') retVal = true; // Override parent scoped return value.
// option 2. Run the closure:
if (closure(val)) retVal = true;
});
return retVal;
}
这里的原因很简单...返回的作用域是不对的。
至少原型对象的版本(一个我居然选中)工作。
感谢Crashalot。我的错。
可能是我,但有没有在你的榜样任何jQuery的特定代码? – gnur 2011-05-24 09:04:13
你只想要索引或对象本身? – 2011-05-24 09:04:18
我想索引我想我可以用grep获得对象。 – Daniel 2011-05-24 09:06:17