通过jquery获取对象数组的索引

FLu*_*enb 2 javascript indexing jquery utility

我有以下数组:

var = array[
            {"id" : "aa", "description" : "some description"},
            {"id" : "bb", "description" : "some more description"},
            {"id" : "cc", "description" : "a lot of description"}]
Run Code Online (Sandbox Code Playgroud)

我试图找到包含的数组的索引id === "bb".我想出的解决方案如下:

var i = 0;
while(array[i].id != "bb"){
   i++;
}
alert(i) //returns 1
Run Code Online (Sandbox Code Playgroud)

有一种更简单的跨浏览器功能吗?我试过$.inArray(id,array)但它不起作用.

mus*_*fan 5

我没有看到代码的复杂性有任何问题,但我建议进行一些更改,包括在值不存在的情况下添加一些验证.您还可以将其全部包装在可重用的辅助函数中......

function getArrayIndexForKey(arr, key, val){
    for(var i = 0; i < arr.length; i++){
        if(arr[i][key] == val)
            return i;
    }
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

然后可以在您的示例中使用它,如下所示:

var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子

注意:这应该是跨浏览器兼容的,并且也可能比任何JQuery替代方案更快.