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
?
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
?
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.
...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];
...
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] == "" )
You could use toString in this case. Careful, there are some outliers where this will not work.
var x = [""]
alert(x.toString() == [""].toString()) // true
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)