Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript if fails with [""] (an array containing an empty string) [duplicate]

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?

like image 461
Fredrick Brennan Avatar asked Aug 12 '26 01:08

Fredrick Brennan


2 Answers

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.

like image 182
Peter Gerasimenko Avatar answered Aug 13 '26 15:08

Peter Gerasimenko


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];
...
like image 28
Robert Koritnik Avatar answered Aug 13 '26 16:08

Robert Koritnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!