I had always wondered why this :
var a = [[0, 1]];
a[0] == [0, 1];
would return false. It seems like these 2 arrays, a[0] and [0, 1], despite not being the same instance of Array, ARE actually the same object, in so far as all their properties are the same. This is not the case in JS though and I don’t know why.
Which test applied to these two arrays, and to much more complicated objects, would return true ? (answers from jQuery and D3.js are accepted, I don’t plan on using any other)
Edit: wrapping the objects with JSON.stringify seems to work; are there any caveats I should be aware of though?
The two objects have the same value but are not the same object, for example if you push a new element to one the other will not get that new pushed element.
Note also that the syntax
[0, 1]is not representing an array object, but it’s an array object “builder” that will produce a new fresh array each time it’s evaluated:For numbers and strings instead equality matches because the referenced objects are immutable (i.e. you can make your variable to point to another number, but you cannot change the number itself).
Calling
JSON.stringifyon an object you get a string representation of the object, not the object… and the representations can indeed match equal for different objects (because they’re just strings).Note that the string representation doesn’t really capture the object, and you can have substantially different objects with the same identical string representation… for example: