如何使用jQuery在JavaScript数组中查找对象的索引
我试图在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"})
有内置的方式吗?
不确定为什么每个()不适合你:
破碎 – 看下面的修正
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);
好吧,我的第一个例子是IS HORKED。 在经过约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; }
这里的原因很简单......回归的范围是错误的。
至少原型对象版本(我实际检查过的版本)有效。
谢谢Crashalot。 我的错。