Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Detecting javascript array type

Status
Not open for further replies.

DebbieLeigh

Programmer
Apr 24, 2004
2
GB
Hi,

Can anyone tell me how I can detect whether a variable is an array in javascript. I've found that typeof returns 'object' for an array, but doesn't go any farther than that.

So, does anyone know of a way to go beyond this and distinguish between arrays and other types of objects?

Debbie-Leigh


 
Code:
if (blah [b]instanceof[/b] Array) alert("Yep, array");
 

You can also compare the "constructor" property:

Code:
<html>
<head>
<script type="text/javascript">
<!--
	var myArrayConstructor = new Array().constructor;
	var myCollectionConstructor = document.getElementsByTagName('body').constructor;

	var myArray = new Array();
	var myCollection = document.getElementsByTagName('body');

	alert(myArray.constructor == myArrayConstructor);
	alert(myCollection.constructor == myCollectionConstructor);
//-->
</script>
</head>
<body>
</body>
</html>

Hope this helps,
Dan
 

Incidentally, I couldn't work out any way to create a new collection without calling a method (such as getElementsByTagName) that returns one.

Does anyone know of a way? I'd be interested to find out. That way, the instanceof could also be used with collections.

Dan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top