JavaScript Lesson 22: Creating Arrays Part 1

<Lesson 21> [Contents] <Lesson 23>

22.1: Introduction to Arrays in JavaScript

An array a regular data structure comprises individual elements that can be referenced to one or more integer index variables, the number of such indices being the number of dimensions or number of elements in the array.In JavaScript, an array is usually represented using the format arrayName[ i ], where i is the index or subscript which represents the position of the element within the array. The array always starts with the zeroth element. For example, an array A of 8 elements comprises elements  A[0], A[1], A[2], A[3], A[4],A[5], A[6], A[7].



Let’s illustrate the above example further. The values of each element shown in the table below:

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
54 60 23 45 67 90 85 34

From the above table, the value of A[0]=54, A[1]=60, A[2]=23  and so forth.

We can perform arithmetic operations on the array elements. For example,

x=A[1]+A[2]+A[3]=137

The above operations add up the values of three array elements and store the sum in the variable x.

22.2 Declaring and Allocating Arrays

In JavaScript, an array can be declared using a number of ways. If the values of the array are unknown or not initialized at the beginning, we use the following statement:

var   A= new Array(12);

which creates an array (or rather array object) that consists of 12 elements. The operator new allocates memory to store 12 elements of the array. The process of creating a new object is known as creating an instance of the object, in this case, an Array object.

Different arrays may be created using one single declaration, separated by commas,as follows:

var x=new Array(20), y=new Array(15), z= new Array(30)

Example 22.1

<head>

<script>

function Start()
{ var A= new Array(10);

for (var i=0; i<A.length;++i)
A[i]=i*10;
for (var i=0; i<A.length;++i)
document.writeln ((“element “+i+” is “+A[i]+”<br>”);
}

</script>

</head>
<body>
</body>

&nsbp;

The output is shown below:

element 0 is 0
element 1 is 10
element 2 is 20
element 3 is 30
element 4 is 40
element 5 is 50
element 6 is 60
element 7 is 70
element 8 is 80
element 9 is 90

Click on Example 22.1 to see the actual output.

Note that we create a function Start to initialize the values of elements in the array using for loop. The results are output using the document.writeln method. The onload method is to initialize the function Start.


<Lesson 21> [Contents] <Lesson 23>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on Reddit