[thelist] JS typeof operator limitations

.jeff jeff at members.evolt.org
Fri Nov 30 15:00:35 CST 2001


rory,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Rory.Plaire at wahchang.com
>
> If an object is an Array.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

ah, but an array *is* an object.

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> Specifically, the document.forms array.
>
> Interestingly if you pass document.forms into a
> function, and document.forms[0] into the same
> function later, you get different results than
> expected.
>
> For instance:
>
> function checkFormSet(formSet)
> {
> 	if(formSet.length > 0)
> 		alert(formSet[formSet.length-1].name;
> }
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

if you call it like this you'll get back the number of forms in the
document:

checkFormSet(document.forms);

however, if you call it like this you'll get back the number of elements in
the first form:

checkFormSet(document.forms[0]);

that's because you're referring to two different level of objects in each
one.  the first is referring to the forms array.  the second is referring to
a specific form in that forms array.  therefore, the length property in your
function will be looking in different places.

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> If you try to check with the typeof operator, you get
> "object" both times.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

correct, most everything in javascript is an object.  some objects happen to
be accessible via a numeric index which we call arrays.  other objects are
available by strings or properties.  these are all still objects though.

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> The only way around this is to check the type
> property... for forms, it is undefined (i.e. == null in
> IE), for elements, it is the type of the element.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

do you get null or 'undefined' when checking the "type" property for a form?
i would think you'd get 'undefined' because there is no "type" property.

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> This seems a little kludgy, but since it works, I'm
> thinking of going for it, unless there is something
> more elegant.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

how you approach the problem will be determined by what you're trying to do
in the first place that's causing the problem.  *grin*  what are you trying
to do that's causing you to encounter this?

thanks,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/






More information about the thelist mailing list