我有对象数组。
像这样的东西:
var arr = new Array(
{x:1, y:2},
{x:3, y:4}
);
当我尝试时:
arr.indexOf({x:1, y:2});
它返回-1
。
如果我有字符串或数字或其他类型的元素而不是对象,则 indexOf()
可以正常工作。
有谁知道为什么要在数组中搜索对象元素,我应该怎么做?
当然,我指的是除了为对象制作字符串散列键并将其提供给数组之外的方法...
最佳答案
indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
您不能使用 ===
来检查对象的相等性。
作为@RobG指出
Note that by definition, two objects are never equal, even if they have exactly the same property names and values.
objectA === objectB
if and only if objectA and objectB reference the same object.
您可以简单地编写自定义 indexOf 函数来检查对象。
function myIndexOf(o) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].x == o.x && arr[i].y == o.y) {
return i;
}
}
return -1;
}
关于javascript - 为什么 Array.indexOf 找不到相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12604062/