CancelImage Upload

How to find out the size of an array in JavaScript

If you are a programmer with experience, yet new to JavaScript, you will no doubt sooner or later be looking for a size of array function, equivalent to the function sizeof() in PHP. In JavaScript this information is returned using the following code:

var arrNames = new Array();

arrNames[0] = "George";

arrNames[1] = "Fred";

arrNames[2] = "Albert";

alert(arrNames.length);

Naturally enough this will return the value 3. As to where this function can be used I have no doubt you will think of a few occasions if you put your mind to it. Setting the top limit for a for loop is just one of the occasions where this piece of code will come in handy:

<html>
<head>
<title>How to define arrays in JavaScript</title>
<script language="JavaScript">

function printArray()
{

      var arrNames = new Array();

      arrNames[0] = "George";

      arrNames[1] = "Fred";

      arrNames[2] = "Albert";

      for(i = 0; i != arrNames.length; i++)
      {

            document.write(arrNames[i] + "<br>");

      }

}

</script>
</head>
<body onload="javascript:printArray();">

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com