3

Possible Duplicate:
JavaScript compare arrays

​var x = [""]
if (x === [""]) { alert(​​"True!") }​​ 
else { alert("False!") }

For some reason, this alerts False. I cannot seem to figure out why. What can I do to make this alert True?

Community
  • 1
  • 1
Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61
  • 12
    Two objects are equal only if they refer to the same object. Even `[] != []`. One simple way to compare them would be to compare their JSON representations. – Blender Jan 03 '13 at 16:51
  • Why should it alert true? You compare two different objects. The happen to have the identical values, but they are still two distinct objects. – Mithrandir Jan 03 '13 at 16:53
  • 1
    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators – j08691 Jan 03 '13 at 16:54
  • @Blender those are arrays, not objects, but your statements still hold for arrays. – jbabey Jan 03 '13 at 17:07
  • 1
    @jbabey: Arrays are objects. – Blender Jan 03 '13 at 17:07

5 Answers5

4

Two objects are equal if they refer to the exact same Object. In your example x is one Object and [""] is another. You cant compare Objects this way. This link maybe useful.

Community
  • 1
  • 1
Peter Gerasimenko
  • 1,906
  • 15
  • 13
2

Compare values not whole arrays

...as they're objects and you're working with implicit references here. One object is stored in your x valiable which you're trying to compare (by reference) with an in-place created object (array with an empty string element). These are two objects each having it's own reference hence not equal.

I've changed your example to do what you're after while also providing the possibility to have an arbitrary number of empty strings in an array:

if (x.length && x.join && x.join("") === "")
{
    alert(​​"True!")
}​
else
{
    alert("False!")
}

This will return True! for any arrays like:

var x = [];
var x = [""];
var x = [null];
var x = [undefined];
var x = ["", null, undefined];
...
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
1

Arrays cannot be reliably compared this way unless they reference the same object. Do this instead:

if ( x[0] == "" )

or if you want it to be an array:

if ( x.length && x[0] == "" )
David G
  • 94,763
  • 41
  • 167
  • 253
0

You could use toString in this case. Careful, there are some outliers where this will not work.

var x = [""]
alert(x.toString() == [""].toString()) // true
jhummel
  • 1,724
  • 14
  • 20
0

In JavaScript, two objects are equal only if they refer to the same object. Even [] == [] is false.

A probably slow but generic solution would be to compare the string representations of the two objects:

JSON.stringify(a1) == JSON.stringify(a2)
Blender
  • 289,723
  • 53
  • 439
  • 496