如何在javascript中查找对象的索引

时间:2018-06-13 10:13:58

标签: javascript arrays angularjs json

我有一个对象数组,我想在我使用indexOf时找到所选对象的索引我得到的值为-1可以有人告诉我如何在javascript中找到对象的indexOf

var a = [{id:2322,location:"Erode",mobile_no:"123456789",name:"andhr",type:"Farmer"}, {id:2323,location:"Coimbatore",mobile_no:"123456789",name:"andhraK",type:"Farmer"}, {id:2324,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}];

a.indexOf({id:2322,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"});

1 个答案:

答案 0 :(得分:1)

那是因为那些不一样。

每个对象获取它自己的内存地址。

address 1: {id:2322,location:"Erode",mobile_no:"123456789",name:"andhr",type:"Farmer"}, 
address 2: {id:2323,location:"Coimbatore",mobile_no:"123456789",name:"andhraK",type:"Farmer"}, 
address 3: {id:2324,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}

然后在数组中存储如下:

var a = [(point to address 1), (point to address 2), (point to address 3)]

当您正在寻找您正在做的对象时

address 4: {id:2322,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}
a.indexOf((point to address 4));

您需要做的是存储您自己对这些对象的引用:



var A = {id:2322,location:"Erode",mobile_no:"123456789",name:"andhr",type:"Farmer"}; 
var B = {id:2323,location:"Coimbatore",mobile_no:"123456789",name:"andhraK",type:"Farmer"};
var C = {id:2324,location:"Erode",mobile_no:"123456789",name:"andhra",type:"Farmer"}

var arr = [A, B, C];
console.log(arr.indexOf(B));