javascript - 为什么 Array.indexOf 找不到相同的对象

标签 javascript arrays search object indexof

我有对象数组。

像这样的东西:

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;
}

演示: http://jsfiddle.net/zQtML/

关于javascript - 为什么 Array.indexOf 找不到相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12604062/

相关文章:

javascript - 获取按下的按键名称

c -++*argv、*argv++、*(argv++) 和 *(++argv) 之间的区别

javascript - 如何在 JavaScript 中搜索全局变量

javascript - 如何知道数组中哪些数据被更改了?

javascript - 在 if/else 中使用 Promise

arrays - Perl - 跨模块的数组哈希

c - 搜索完整的哈希表

database - 查找一组中最相似的匹配项

javascript - 打破 Mongoose 中的 Bluebird promise 链

javascript - 将表单数据序列化为 JSON 时如何保留值类型