PDA

View Full Version : Resolved These two arrays look the same - JS says they aren't.



jlizarraga
11-03-2008, 08:20 PM
I have two arrays that are populated a bit differently, but when they end up with the same content, my check reports that they are in fact different:

http://img224.imageshack.us/img224/7005/wtfhs9.gif

The length property of both arrays is 16, and as you can see by the alert those 16 elements are indeed the same.

Here is the code popping the alert:


if(array1 != array2){
alert("Javascript thinks the following are unequal:\n" + array1 + "\n" + array2);
}

What factors can cause two seemingly identical arrays like this to evaluate to unequal? Any help greatly appreciated!

jscheuer1
11-03-2008, 08:39 PM
An array is an object, not a string. Two objects are not equal unless they are the same object, just containing the same elements or properties is not enough. Since these aren't multidimensional arrays and all of the items are strings, you could test each item in one array against its counterpart in the other to see if they are equivalent, but they will never be equal in the strict javascript sense of the term as regards objects.

Here's an easy but not foolproof method of checking the equivalency of items:


if(array1.join('$?!422') == array2.join('$?!422')) alert('arrays equivalent');

This will work as long as none of the single elements in either array mimic two in the other in proper order and sequence with $?!422 strategically placed in that item. Also, this assumes two single dimensional arrays containing only strings or numbers.

jlizarraga
11-03-2008, 08:55 PM
Thanks a ton as usual, John!