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

前端 未结 1 1653
终归单人心
终归单人心 2021-01-12 11:43

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:



        
相关标签:
1条回答
  • 2021-01-12 12:22

    Not sure why each() doesn't work for you:

    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. : )

    Properly, check() should look like this:

    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.

    0 讨论(0)
提交回复
热议问题