Open Directory Site JavaScript Tutorials

ASP | XML | VBScript | JavaScript | ADO | CSS | XMLDOM | PHP | Operating Systems

Home >> JavaScript >> JavaScript Array Object

 JavaScript Array Object

 

The Array object

Some times you want to assign more than one value to a single variable. Then you can create a variable that can contain a series of values. This is called an array variable. The declaration of an array variable:

names = new Array(3)

The expecting number of elements goes inside the parentheses, in this case 3. You assign data to each of the elements of the array like this:

names[0] = "Tove"

names[1] = "Jani"

names[2] = "Ståle"

Similarly, the data can be retrieved from any element using an index into the particular array element you want. Like this:

mother = names[0]

Examples

1. Arrays are used to store a series of related data items. This example demonstrates how you can make an array that stores names.

Coding

<html>

<body>

<script language="JavaScript">

var famname = new Array(6)

famname[0] = "Jan Egil"

famname[1] = "Tove"

famname[2] = "Hege"

famname[3] = "Ståle"

famname[4] = "Kai Jim"

famname[5] = "Børge"

for (i=0; i<6; i++)

{

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

}

</script>

</body>

</html>

Output

Jan Egil

Tove

Hege

Ståle

Kai Jim

Børge

2.This is another way of making an array that gives the same result as the one above. Note that the length method is used to find out how many elements the array contains.

Coding

<html>

<body>

<script language="JavaScript">

var famname = new Array("Jan Egil","Tove","Hege","Ståle","Kai Jim","Børge")

for (i=0; i<famname.length; i++)

{

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

}

</script>

</body>

</html>

Output

Jan Egil

Tove

Hege

Ståle

Kai Jim

Børge

Cheap Web Hosting Articles - Web Site Design & Web Hosting Tutorials - Domain Hosting