[英]How to find index of object in a JavaScript array with jQuery
I am trying to find the index of an object in an array in jquery.我试图在 jquery 的数组中找到 object 的索引。 I cannot use jQuery.inArray because i want to match objects on a certain property.
我不能使用 jQuery.inArray 因为我想匹配某个属性上的对象。 I am using:
我在用:
jQuery.inObjectArray = function(arr, func)
{
for(var i=0;i<arr.length;i++)
if(func(arr[i]))
return i;
return -1;
}
and then calling:然后调用:
jQuery.inObjectArray([{Foo:"Bar"}], function(item){return item.Foo == "Bar"})
Is there a built in way?有内置的方法吗?
Not sure why each() doesn't work for you:不知道为什么 each() 不适合你:
BROKEN -- SEE FIX BELOW坏了——见下面的修复
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;
}
Additional example for Op comments. 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);
Ok, my first example IS HORKED.好的,我的第一个例子是吓坏了。 Pointed out to me after some 6 months and multiple upvotes.
在大约 6 个月后向我指出并多次投票。 : )
:)
Properly, check() should look like this:正确地, 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;
}
The reason here is pretty simple... the scoping of the return was just wrong.这里的原因很简单……回报的范围是错误的。
At least the prototype object version (the one I actually checked) worked.至少原型 object 版本(我实际检查过的那个)工作正常。
Thanks Crashalot.谢谢克拉沙洛特。 My bad.
我的错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.