Web Development Tutorials




  
  

Creating Arrays

Program loops are often used in building and accessing arrays. An array is a sequence of storage locations in memory. Whereas a standard variable can hold only one item of data at a time, an array can hold many items of data under the same variable name. Each item, or element, in an array is accessed by an index number that refers to the item's position in the array.

The following illustration represents a JavaScript array named greek containing the first five letters of the Greek alphabet.

greek
alphagreek[0]
betagreek[1]
gammagreek[2]
deltagreek[3]
epsilongreek[4]

Figure 6-1. An array with five elements.


Array elements are numbered starting with 0 (zero) as the index of the first item in the array. Each data item in the array is referenced by its position, with its index number appearing in brackets [ ] following the array name. Thus, a reference to variable greek[0] is a reference to data value "alpha", a reference to greek[1] points to data item "beta", and so forth through the above array. When working with a large number of similar data items, it is much more convenient to package them and access them as an array, rather than storing them as separate, individually named variables.

Array Objects

An array is created by first creating an array object and then assigning data to the individual elements of the array. An array is created with a JavaScript statement in the format shown below.


var array = new Array();

Figure 6-2. General format to create an array.


The array is a variable name that follows JavaScript naming conventions and through which its elements are referenced. The array is created as a new Array() object. If you know in advance the number of items occupying the array, that number can be enclosed in the parentheses to dimension the array for that number of items. Otherwise, it is created as an empty array that expands as items are added to it.

The Greek array shown above is created with the specification


var greek = new Array();

Once the array is created it is loaded with data values. This is done be assigning a value to each element of the array, using an index number to indicate the locational element to which the data item is assigned. An array can store either strings or numbers.


greek[0] = "alpha";
greek[1] = "beta";
greek[2] = "gamma";
greek[3] = "delta";
greek[4] = "epsilon";

After it is filled with data values, the array's length property (greek.length) gives the number of elements in the array. Because array elements are numbered beginning with 0, the length is always one more than the highest index number.

Filling an Array

Of course, if you are working with a large array it can be tedious to enter data into the array one item at a time as is done here. However, this is the only choice unless generating values programmatically. Since JavaScript does not permit access to external files or databases as sources of array data, array values must be hand entered or generated by the local script.

If array data are amenable to script generation, then it is relatively simple to fill an array using a program loop. The following script creates an array and fills it with the square roots of the numbers 1 through 10.



Figure 6-3. Building and displaying an array.


function buildArray()
{
  var squareRoots = new Array();
  for (i=0; i<10; i++) {
    squareRoots[i] = Math.sqrt(i + 1).toFixed(3);
  }
	
  var tableOut = ""
  tableOut += "<table border='1' style='width:100px'>";
  tableOut += "<caption>SquareRoots</caption>";
  for (i=0; i < squareRoots.length; i++) {
    tableOut += "<tr><td style='text-align:center'>" + 
      squareRoots[i] + "</td></tr>";
  }
  tableOut += "</table>";
  document.getElementById("output").innerHTML = tableOut;
}

function init()
{
  var buildArrayBtn = document.getElementById("buildArrayBtn");
  buildArrayBtn.onclick=buildArray;
}

window.onload=init;

<input type="button" value="Build Array" id="buildArrayBtn"/>
<p><div id="output"></div></p>

Listing 6-1. Code to build and display an array.

Array squareRoots is created as an empty array. Then a for loop is set up to increment through elements 0 - 9 to create the 10 storage positions in the array. Each array element, squareRoot[i], is assigned the square root of the loop index plus 1, Math.sqrt(i + 1), stored to three decimal positions. Thus, the square roots of the numbers 1 - 10 are stored in elements 0 - 9 of the array.

A second loop iterates the array to display its contents.


for (i=0; i < squareRoots.length; i++) {
  ...
}

Recall that the length property of an array gives its size in number of elements. Since an array is indexed beginning with 0, the last element in the array has an index value that is one less than its length. Therefore, as long as index i < squareRoot.length the script displays the value of the array element.


TOP | NEXT: Accessing Arrays