Javascript oddness with array of objects and indexOf

拥有回忆 提交于 2019-11-27 02:09:46

Array.indexOf() will only work on objects if the supplied object is exactly the same object you put in.

An exact copy is insufficient, it has to be the exact same object, i.e. there must be some object in the array such that:

arr[i] === obj

You need to show how you retrieved the object.

I would like to see the retrieve function, but most likely you are not using the same reference. Because the following is true:

var a = {id: 3};
var b = [a];
b.indexOf(a); // 0
a.id = "not three";
b.indexOf(a); // still 0

However, the following will break:

var a = {id: 3};
var b = [{id: 3}];
b.indexOf(a); // -1 not the same object
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!