Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #9393
| From | "J.R." <groups_jr-1@yahoo.com.br> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Re: Undefined array element becomes defined and null |
| Date | 2011-12-19 00:48 -0200 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <jcm8li$ggp$1@speranza.aioe.org> (permalink) |
| References | <timstreater-96FB3B.23374518122011@news.individual.net> |
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.)
Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread
Undefined array element becomes defined and null Tim Streater <timstreater@greenbee.net> - 2011-12-18 23:37 +0000
Re: Undefined array element becomes defined and null Stefan Weiss <krewecherl@gmail.com> - 2011-12-19 03:17 +0100
Re: Undefined array element becomes defined and null Tim Streater <timstreater@greenbee.net> - 2011-12-19 09:17 +0000
Re: Undefined array element becomes defined and null Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-12-19 13:13 +0100
Re: Undefined array element becomes defined and null "Evertjan." <exjxw.hannivoort@interxnl.net> - 2011-12-19 16:42 +0000
Re: Undefined array element becomes defined and null "J.R." <groups_jr-1@yahoo.com.br> - 2011-12-19 00:48 -0200
csiph-web