Wrox Home  
Search P2P Archive for: Go

  Return to Index  

javascript thread: Check if an object is a String or an Array


Message #1 by "Greg Dunn" <greg.dunn@n...> on Wed, 26 Sep 2001 17:36:34 -0500
Thanks to all.  instanceof worked great.  I missed it in my reference 
since it's JavaScript 1.4.  Compatibility might have been an issue, but 
I'm lucky in this case since this is an Intranet applicaton and we're 
standardized on IE 5.

Greg


> Could use the instanceof operator, something like:
> var arrOne = new Array();
> var arrTwo = new Array();
> var sOne = new String("Hello");
> var sTwo = "Hello";
> arrOne[0] = sOne;
> arrOne[1] = arrTwo;
> arrOne[2] = sTwo;
> for (var i = 0; i < arrOne.length; i++)
> {
>   if (arrOne[i] instanceof String)
>   {
>     WScript.echo("String");
>   }
>   else if (arrOne[i] instanceof Array)
>   {
>     WScript.echo("Array");
>   }
>   else
>   {
>     WScript.echo("Neither");
>   }
> }
> That's a stand-alone script, obviously replace WScript.echo with alert 
or 
> whatever if necessary.
> Regards
> 
> Joe Fawcett
> 
> 
> 
> >From: "Greg Dunn" <greg.dunn@n...>
> >Reply-To: "javascript" <javascript@p...>
> >To: "javascript" <javascript@p...>
> >Subject: [javascript] Check if an object is a String or an Array
> >Date: Wed, 26 Sep 2001 17:36:34 -0500
> >
> >Hi:
> >
> >I need to determine whether an element in an array is a String 
containing 
> >an
> >HTML link or an array.  I will be one or the other.
> >
> >The code is below.  I tried to use 'foldersNode[i].match' (and indexOf) 
but
> >of course I get an error if foldersNode[i] is an array.  I understand 
that
> >much, but I can't figure out how to get this to work.  TIA!
> >
> >
> >for (i=4; i < foldersNode.length; i++) {
> >    if (i == foldersNode.length - 1) {
> >       if (foldersNode[i].match("<A href")) //<-- ERROR
> >	   displayDocument(foldersNode[i], doc, level, 1, leftside)
> >	   // ^do this if it's an HTML link string
> >	else
> >	   redrawNode(foldersNode[i], doc, level, 1, leftSide)
> >	   // ^otherwise do this, (it's an array)
> >    }
> >    else {
> >	if (foldersNode[i].match("<A href"))
> >	   displayDocument(foldersNode[i], doc, level, 0, leftSide)
> >	else
> >	   redrawNode(foldersNode[i], doc, level, 0, leftSide)
> >	}
> >}
> >
> >Greg

  Return to Index