为什么 Array.indexOf 找不到相同的对象 [英] Why Array.indexOf doesn't find identical looking objects

查看:63
本文介绍了为什么 Array.indexOf 找不到相同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含对象的数组.

像这样:

var arr = new Array({x:1, y:2},{x:3, y:4});

当我尝试时:

arr.indexOf({x:1, y:2});

它返回-1.

如果我有字符串或数字或其他类型的元素而不是对象,那么 indexOf() 工作正常.

有谁知道为什么要搜索数组中的对象元素以及我应该怎么做?

当然,我的意思是除了为对象制作字符串哈希键并将其赋予数组之外的方法......

解决方案

indexOf 使用严格相等(与 === 或三重相等运算符使用的方法相同)将 searchElement 与 Array 的元素进行比较.

您不能使用 === 来检查对象的平等性.

正如 @RobG 指出的

<块引用>

请注意,根据定义,两个对象永远不会相等,即使它们具有完全相同的属性名称和值.objectA === objectB 当且仅当 objectA 和 objectB 引用同一个对象.

您可以简单地编写一个自定义的 indexOf 函数来检查对象.

function myIndexOf(o) {for (var i = 0; i < arr.length; i++) {如果 (arr[i].x == o.x && arr[i].y == o.y) {返回我;}}返回-1;}

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

I have array with objects.

Something Like this:

var arr = new Array(
  {x:1, y:2},
  {x:3, y:4}
);

When I try:

arr.indexOf({x:1, y:2});

It returns -1.

If I have strings or numbers or other type of elements but object, then indexOf() works fine.

Does anyone know why and what should I do to search object elements in array?

Of course, I mean the ways except making string hash keys for objects and give it to array...

解决方案

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

You cannot use === to check the equability of an object.

As @RobG pointed out

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.

You can simply write a custom indexOf function to check the object.

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

DEMO: http://jsfiddle.net/zQtML/

这篇关于为什么 Array.indexOf 找不到相同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆