On 18/12/2011 21:37, Tim Streater wrote:
> I have a JavaScript array, myArray. I happen to know that let's say
> element 27 is undefined - it's never been created. It appears that I can
> detect this with:
>
> if (myArray[27]==null)
> {
> alert (myArray[27]);
> }
>
>
> The alert puts up 'undefined'. Is it valid to be able to detect the
> undefined stater of element 27 in this way?
>
> Initially I thought perhaps that the act of accessing the element
> created it and set it to null, but apparently not if the alert is
> anything to go by. Or is this just a quirk of Safari?
In this particular case, we should use the strict Equals Operator (===)
than just the Equals Operator (==), because undefined == null, for
instance, produces true, whereas undefined === null yields false.
Note: Douglas Crockford's advice is to never use [what he calls] the
evil twins (== and !=). Instead, we should always use === and !==,
although Crockford's advice is a tad exaggerated when dealing with the
typeof operator which always returns a string value.
Another important thing: if we access a missing array element, we will
get the undefined value, not null. So, the OP's code might be rewritten to:
var missingElem = myArray[27];
if (typeof missingElem == 'undefined') {
alert('this is a missing element in myArray');
}
--
Joao Rodrigues (J.R.)
|