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

我有以下数组:

var = array[ {"id" : "aa", "description" : "some description"}, {"id" : "bb", "description" : "some more description"}, {"id" : "cc", "description" : "a lot of description"}] 

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

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

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

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

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

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

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

这是一个有效的例子

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

 var myArray = [your array]; var i = 0; $.each(myArray, function(){ if (this.id === 'bb') return false; i++; }) console.log(i) // will log '1' 

用现代JS更新。

 let index myArray.map(function(item, i){ if (item.id === 'cc') index = i }) console.log(index) // will log '2' 

inArray无法使用多维数组,请尝试以下操作

 var globalarray= [ {"id" : "aa", "description" : "some description1"}, {"id" : "bb", "description" : "some more description"}, {"id" : "cc", "description" : "a lot of description"}]; var theIndex = -1; for (var i = 0; i < globalarray.length; i++) { if (globalarray[i].id == 'bb') { theIndex = i; break; } } alert(theIndex); 

演示

你可以使用jQuery.each – http://api.jquery.com/jQuery.each/

 var i; jQuery.each(array, function(index, value){ if(value.id == 'bb'){ i = index; return false; // retrun false to stop the loops } }); 
 Object.keys(yourObject).indexOf(yourValue);