CancelImage Upload

How to define arrays in JavaScript

If you are new to programming this article will introduce you to the advantage of arrays over standard variables. While for experienced programmers this guide merely serves as a reference in regard to how arrays are defined in JavaScript.

What is an array

Let's say you have a list of names. Now if you wanted to implement this list into your code you could either define a list of variables (name1, name2, name3), or you could load them into an open ended array:

var arrNames = new Array();

arrNames[0] = "George";

arrNames[1] = "Fred";

arrNames[2] = "Albert";

One of the keys for the array arrNames successfully to be brought into existence is the initialisation of the array's name:

var arrNames = new Array();

If you are asking yourself for what an array might be useful the answer is simple. Let us say for instance that you want to return each name within our script. Now if each name was given to an individual variable we would have to look each one up and print them out individually. With arrays we can just make use of a simple loop:

<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 != 3; 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