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

标签 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([{Foo:"Bar"}], function(item){return item.Foo == "Bar"})

有内置的方法吗?

最佳答案

不确定为什么 each() 对你不起作用:

损坏 -- 请参见下面的修复

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);

好吧,我的第一个例子是 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;
}

原因很简单……返回的范围是错误的。

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

谢谢 Crashalot。我的错。

关于javascript - 如何使用 jQuery 在 JavaScript 数组中查找对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6108034/

相关文章:

java - Gui 中的数组递增

javascript - 加载页面时如何使用 JQuery 向左移动(隐藏)<div>?

javascript - 单击带有标签的单选按钮

javascript - pagebeforehide 事件仅针对 "inner"页面转换而触发

c - 重新分配多维数组

javascript - 通过按多个标准对集合进行排名来对集合进行排序

javascript - JS : Passed JSON-Array loses quotation marks

javascript - 未在加载时定义

javascript - 为所有表单元素添加一个 onBlur

javascript - Flot 刻度转子显示刻度两次