在Javascript中,为什么[1,2] == [1,2]或({a:1})==({a:1})为假? [英] In Javascript, why is [1, 2] == [1, 2] or ({a : 1}) == ({a : 1}) false?
问题描述
以下是在Firebug中完成的:
The following is done in Firebug:
>>> [1, 2] == [1, 2]
false
>>> ({a : 1}) == ({a : 1})
false
我认为Javscript有一些规则说,如果一个Object或Array对相同的元素有相同的引用,那么它们是相等的吗?
I thought Javscript has some rule that says, if an Object or Array has the same references to the same elements, then they are equal?
但即使我说
>>> foo = {a : 1}
Object { a=1}
>>> [foo] == [foo]
false
>>> ({a: foo}) == ({a: foo})
false
是否有办法使它能够进行元素比较并返回 true
?
Is there a way to make it so that it can do the element comparison and return true
?
推荐答案
{}
和 []
与新对象相同
和 new Array
和 new Object!= new对象
(与数组
同上)因为它们是新的和不同的对象。
And new Object != new Object
(ditto with Array
) because they are new and different objects.
如果你想知道两个任意对象的内容是否相同,那么快速(但很慢)修复是
If you want to know whether the content of two arbitary objects is the "same" for some value of same then a quick (but slow) fix is
JSON.parse(o)=== JSON.parse(o)
一个更优雅的解决方案定义一个相等的函数(未经测试)
A more elegant solution would be to define an equal function (untested)
var equal = function _equal(a, b) {
// if `===` or `==` pass then short-circuit
if (a === b || a == b) {
return true;
}
// get own properties and prototypes
var protoA = Object.getPrototypeOf(a),
protoB = Object.getPrototypeOf(b),
keysA = Object.keys(a),
keysB = Object.keys(b);
// if protos not same or number of properties not same then false
if (keysA.length !== keysB.length || protoA !== protoB) {
return false;
}
// recurse equal check on all values for properties of objects
return keysA.every(function (key) {
return _equal(a[key], b[key]);
});
};
警告:写作在所有输入上工作的相等函数很难,一些常见的问题是(null == undefined)=== true
和(NaN = == NaN)=== false
我在我的函数中都没有。
Warning: writing an equality function that "works" on all inputs is hard, some common gotchas are (null == undefined) === true
and (NaN === NaN) === false
neither of which I gaurd for in my function.
我没有处理任何跨浏览器问题,我只是假设ES5存在。
Nor have I dealt with any cross browser problems, I've just assumed ES5 exists.
这篇关于在Javascript中,为什么[1,2] == [1,2]或({a:1})==({a:1})为假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!