我试图在 jquery 的数组中查找对象的索引。
我无法使用 jQuery.inArray 因为我想匹配某个属性上的对象。
我在用:
jQuery.inObjectArray = function(arr, func)
{
for(var i=0;i<arr.length;i++)
if(func(arr[i]))
return i;
return -1;
}
然后调用:
jQuery.inObjectArray([{Foo:"Bar"}], function(item){return item.Foo == "Bar"})
有内置的方法吗?
不确定为什么 every() 不适合你:
损坏 - 请参阅下面的修复
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;
}
Op 评论的附加示例。
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);
好吧,我的第一个例子已经被吓住了。经过大约 6 个月和多次点赞后向我指出。 :)
正确地, check() 应该如下所示:
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;
}
这里的原因很简单......返回的范围是错误的。
至少原型对象版本(我实际检查过的版本)有效。
谢谢克拉萨洛特。我的错。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)