An array is an ordered collection of values referenced by a single variable. The syntax for creating an array variable is:
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:
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:
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/JavaScript | Comments |
---|---|
<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 |