Creating arrays

An array is an ordered collection of values referenced by a single variable. The syntax for creating an array variable is:

var variable = new Array(size);

where variable is the name of the array variable and size (optional parameter) is the number of elements in the array. Once an array is created, its entries can be accessed by using the array variable along with the entry index put in brackets:

variable[index]

where index is a non-negative integer value. The first array element has index 0.

In the following example an array of 10 elements is created. The array elements are color names:

var colors = new Array(10);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "red";
colors[3] = "yellow";
colors[4] = "white";
colors[5] = "cyan";
colors[6] = "brown";
colors[7] = "magenta";
colors[8] = "lightblue";
colors[9] = "orange";

This array is used in the next script for changing the background color of this page in a cyclic order according to the value stored in the array:

     

The complete code looks as follows:

HTML/JavaScriptComments
<form>
  <input type="button" value=" change color " 
      onclick="changeColor()">
  <input type="button" value="reset" 
      onclick="document.bgColor='#CCCC99'">
</form>
<script type="text/javascript">
var colors = new Array(10);
    colors[0] = "green";
    colors[1] = "blue";
    colors[2] = "red";
    colors[3] = "yellow";
    colors[4] = "white";
    colors[5] = "cyan";
    colors[6] = "brown";
    colors[7] = "magenta";
    colors[8] = "lightblue";
    colors[9] = "orange";
var i = 0;
function changeColor()
{
    document.bgColor = colors[i];
    i = (i+1) % 10;
}
</script>

button for changing the background
 calling changeColor() function
buttor to reset the background
 action assigned with the button

creating array of color names











i is the next color to be used


setting the background
incrementing i on 1 cyclically