JavaScript的array.indexOf不搜索对象 [英] Javascript array.indexOf doesn't search objects

查看:117
本文介绍了JavaScript的array.indexOf不搜索对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组。

是这样的:

  VAR ARR =新阵列(
  {X:1,Y:2},
  {X:3,Y 4}
);

当我尝试

  arr.indexOf({X:1,Y:2});

返回-1。

如果我有一个字符串,数字或其他类型的元素,但对象,那么的indexOf()的罚款。

有谁知道为什么,我应该怎样做才能在阵列搜索obect元素呢?

当然,我指的是除方法使字符串哈希键的对象,并给它数组...


解决方案

  

的indexOf searchElement比较使用全等(由===用同样的方法,或三等号,运营商)的数组的元素。


您不能使用 === 来检查对象的均衡性。

作为<一个href=\"http://stackoverflow.com/questions/12604062/javascript-array-indexof-doesnt-search-objects/12604120#comment16989045_12604062\">@RobG指出


  

请注意,根据定义,两个对象从未相等,即使它们具有完全相同的属性名和值。 对象A ===对象B 当且仅当对象A和对象B引用同一个对象。


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

 函数myIndexOf(O){
    对于(VAR I = 0; I&LT; arr.length;我++){
        如果(ARR [I] .X == o.x&放大器;&安培;常用3 [I] .Y == o.y){
            返回我;
        }
    }
    返回-1;
}

DEMO: 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 obect 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/

这篇关于JavaScript的array.indexOf不搜索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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