为什么Array.indexOf找不到相同的外观对象 [英] Why Array.indexOf doesn't find identical looking objects
问题描述
我有对象数组。
像这样:
var arr = new Array(
{x:1, y:2},
{x:3, y:4}
);
当我尝试:
arr.indexOf({x:1, y:2});
它返回 -1
。
如果我有字符串或数字或其他类型的元素但是对象,则 indexOf()
工作正常。
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将searchElement与使用严格相等的数组元素(与===或三重等于运算符使用的方法相同)。
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 指出
注意,根据定义,两个对象永远不会相等,即使它们是h ave完全相同的属性名称和值。
objectA === objectB
当且仅当objectA和objectB引用同一个对象时。
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函数来检查对象。
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屋!