1

This is a general question about javascript object ontology and the way the === operator works.

start with an example:

var z = [1]; 
z === [1] // returns false.

Totally blew my mind. Why??

I guess it has to be that === is comparing the array as an object (i.e. by its object id or whatever), than by comparing the contents of the object--which would return true.

So what is a good way to compare the contents of an object like that?

You can force the issue by converting z.toString(), and comparing the result, but this seems crude.

gipinani
  • 14,038
  • 12
  • 56
  • 85
T. Rexman
  • 73
  • 3
  • possible duplicate of [Difference between == and === in JavaScript](http://stackoverflow.com/questions/523643/difference-between-and-in-javascript) – Marc B Jun 06 '14 at 18:20
  • The first part is actually assigning (with the '=', not comparing). Can you post an actual snippet of working code please? – Mike Cheel Jun 06 '14 at 18:23
  • What's not working about the example @MikeCheel? He *meant* for the first part to be assigning, to show that after assigning `[1]` to `z`, when he then compared it to `[1]` it returned false – Tom Jun 06 '14 at 19:57
  • I was just pointing it out because MarcB mentioned eh thought it was similar to the difference between == and === – Mike Cheel Jun 06 '14 at 20:20
  • yeah i meant the first = to be an assignment, Tom's got it. The answer below hit the nail on the head, or at least confirmed my speculation, although I'd still like to know if .toString() is the best way of comparing the contents of two arrays, short of recursively iterating through and checking each item to make sure it's the same as the corresponding value in the other array (and recursing down in case the item is an array or object instead of an array). – T. Rexman Jun 07 '14 at 15:20

1 Answers1

0

You cannot compare two non-primitives values in javascript with == or === . The result is false, even if their structures and values are equals, because the comparison is not on the values but on the adress of the objects.

Example

z = [5];
a = z;
b = z;
a === b; // true, because a and b linked to z.

And to answer the question of "How to compare", you can effectively tostring, or make a loop on the two arrays...

  • Thanks! I think converting to a string works to compare the contents of arrays as long as the array items are strings or numbers, and it doesn't matter if the numbers were kept as strings or numbers, since toString() loses that information. But toString doesn't work if you're comparing the contents of key-value-pair-objects, since toString()-ing an object returns [object Object], which isn't very helpful. This is all in the Chrome browser console, by the way, in case that matters for this issue. – T. Rexman Jun 07 '14 at 04:21