Javascript arrays are objects and you can't simply use the equality operator ==
to understand if the content of those objects is the same. The equality operator will only test if two object are actually exactly the same instance (e.g. myObjVariable==myObjVariable
, works for null
and undefined
too).
If you need to check if two array are equals i'd recommend to just traverse both arrays and verify that all the elements have the same value (and that the two array have the same length).
Regarding custom objects equality i'd build instead a specific equals
function and i'd add it to the prototype of your class.
Considering that in the end you converted both arrays to a String
and tested equality of the resulting strings, you could one day consider using a similar but more generic technique you'll find described in more than a few places:
JSON.stringify(OBJ1) === JSON.stringify(OBJ2)
Well, don't.
While this could work if the order of the properties will always the same for those object instances, this leaves the door open for extremely nasty bugs that could be hard to track down. Always favor a more explicit approach and just write a clean and readable function that will test for equality checking all the required fields.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…