如何使用 jQuery 在 JavaScript 数组中查找对象的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6108034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:29:32  来源:igfitidea点击:

How to find index of object in a JavaScript array with jQuery

javascriptjqueryarrays

提问by Daniel

I am trying to find the index of an object in an array in jquery. I cannot use jQuery.inArray because i want to match objects on a certain property. I am using:

我试图在 jquery 的数组中找到对象的索引。我不能使用 jQuery.inArray 因为我想匹配某个属性上的对象。我在用:

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?

有内置的方法吗?

采纳答案by John Green

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.

操作注释的附加示例。

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.

至少原型对象版本(我实际检查过的那个)有效。

Thanks Crashalot. My bad.

谢谢克拉夏洛特。我的错。