I'm having an interesting issue that I'm sure is easily explained, but the explanation is eluding me.
An undefined or null object in javascript is equal to false.
var x;
alert(!x); //returns true
alert(x==true); //returns false
What about an empty array object? Is that the equivalent of true or false?
var x = [];
alert (x==true); //returns false
alert (!x); //returns false
If it is equivalent to true, how do I check if it's non-empty? I was hoping to do
if (!x) {
//do stuff
}
I tried checking x.length
, but I'm using this object as a map:
var x = [];
alert(x.length); //returns 0
x.prop = "hello";
alert(x.length); //still returns 0
How can I check if my map is empty?
It's not as easy as it looks, you have to check that the object has at least one property.
jQuery provides isEmptyObject
for that purpose:
function isEmptyObject( obj ) {
for ( var name in obj ) {
return false;
}
return true;
}
Sample usage:
> var x = [];
> x.prop = "hello";
> isEmptyObject(x);
false
Little confused as you seem to be mixing objects and arrays in your question. Hopefully this might help clear it up for you.
An empty array evaluates to true:
!![] //true
But integer 0 evaluates to false, so you can do:
!![].length //false
So:
if([].length) {
//array has 1 element at least
} else {
//array has 0 elements
}
However you do seem to be getting arrays and objects confused. In JavaScript, we have objects:
var x = {};
x.foo = "bar";
x.baz = 2;
And we have arrays:
var x = [];
x.push("foo");
x.length //1
You can't do what you do in your opener:
var x = []; //x is an array
x.foo = "bar"; //can't do this on an array
x.length; // 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With