The following is done in Firebug:
>>> [1, 2] == [1, 2]
false
>>> ({a : 1}) == ({a : 1})
false
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?
But even if I say
>>> foo = {a : 1}
Object { a=1}
>>> [foo] == [foo]
false
>>> ({a: foo}) == ({a: foo})
false
Is there a way to make it so that it can do the element comparison and return true?
{ }and[ ]are the same asnew Objectandnew ArrayAnd
new Object != new Object(ditto withArray) 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)
equalsexampleWarning: writing an equality function that “works” on all inputs is hard, some common gotchas are
(null == undefined) === trueand(NaN === NaN) === falseneither of which I gaurd for in my function.Nor have I dealt with any cross browser problems, I’ve just assumed ES5 exists.