Arrays

Contact Us or call 1-877-932-8228
Arrays

Arrays

An array is a grouping of objects that can be accessed through subscripts. At its simplest, an array can be thought of as a list. In JavaScript, the first element of an array is considered to be at position zero (0), the second element at position one (1), and so on. Arrays are useful for storing related sets of data.

Arrays are declared using the new keyword.

var myarray = new Array();

It is also possible and very common to use the [] literal to declare a new Array object.

var myarray = [];

Values are assigned to arrays as follows:

myarray[0] = value1;
myarray[1] = value2;
myarray[2] = value3;

Arrays can be declared with initial values.

var myarray = new Array(value1, value2, value3);
//or, using the [] notation:
var myarray = [value1, value2, value3];

The following example is similar to the previous one, except that it prompts the user for four different colors and places each into the userColors array. It then displays the values in the userColors array in the spans and assigns them to document.body.style.backgroundColor when the user clicks on the spans.

Unlike in some languages, values in JavaScript arrays do not all have to be of the same data type.

Code Sample:

VariablesArraysOperators/Demos/Arrays.html
---- C O D E   O M I T T E D ----

<script>
	//Pop up four prompts and create an array
	var userColors = new Array();
	userColors[0] = window.prompt("Choose a color.", "");
	userColors[1] = window.prompt("Choose a color.", "");
	userColors[2] = window.prompt("Choose a color.", "");
	userColors[3] = window.prompt("Choose a color.", "");
</script>
</head>
<body>
<p>
	<span onclick="document.body.style.backgroundColor = userColors[0];">
	<script>
		document.write(userColors[0]);
	</script>
	</span> |
	<span onclick="document.body.style.backgroundColor = userColors[1];">
	<script>
		document.write(userColors[1]);
	</script>
	</span> |
	<span onclick="document.body.style.backgroundColor = userColors[2];">
	<script>
		document.write(userColors[2]);
	</script>
	</span> |
	<span onclick="document.body.style.backgroundColor = userColors[3];">
	<script>
		document.write(userColors[3]);
	</script>
	</span>
</p>
</body>
</html>

Code Explanation

As the page loads, an array called userColors is declared.

userColors = new Array();

The next four lines populate the array with user-entered values.

userColors[0] = window.prompt("Choose a color.", ""); userColors[1] = window.prompt("Choose a color.", ""); userColors[2] = window.prompt("Choose a color.", ""); userColors[3] = window.prompt("Choose a color.", "");

The body of the page contains a paragraph with four span tags, the text of which is dynamically created with values from the userColors array.

Next