如何使用jQuery在JavaScript数组中查找对象的索引
我试图在jquery中查找数组中对象的索引。 我无法使用jQuery.inArray,因为我想匹配某个属性上的对象。 我正在使用:如何使用jQuery在JavaScript数组中查找对象的索引,javascript,jquery,arrays,Javascript,Jquery,Arrays,我试图在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 = function(arr, func)
{
for(var i=0;i<arr.length;i++)
if(func(arr[i]))
return i;
return -1;
}
是否有内置方式?不确定为什么每个()都不适合您:
坏了--请参见下面的修复
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);
原因很简单。。。回报的范围是错误的
至少原型对象版本(我实际检查的版本)起作用了
谢谢克拉夏洛。我的错。可能是我,但您的示例中是否有任何特定于jQuery的代码?您是只想要索引还是对象本身?我想要索引,我想我可以通过grep获得对象。可能他使用了
$(arr)。each()
谢谢。我实际上在寻找一个像inArray这样的函数,就像我在上面写的函数那样,它不会让我创建一个像你刚才创建的函数。所以,我要澄清的是,有没有一个内置的函数,可以完成你的函数所做的事情。但也许我看得太远了。事实上,我不喜欢jQuery的这种说法。。。。这些名字都太多了。当然,硬币的另一面类似于PHP,它有数百个没有名称空间的顶级函数。@Daniel-不,但这是JavaScript的要点。我添加了一个额外的示例,它展示了如何获取核心对象并通过其原型对其进行扩展。一般来说,这是一种更高级的技术,而且肯定会有自己的问题,因为它不是非常原子化的。嗨,John,你是如何绕过jQuery.each的这一方面的(取自jQuery API):“我们可以打破$.each()通过使回调函数返回false,在特定迭代中循环。返回non-false与for循环中的continue语句相同;它将立即跳到下一个迭代。”
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);
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;
}