HTML and CSS Reference
In-Depth Information
Working with arrays
Arrays are JavaScript objects and are created just like any other JavaScript object, with the
new keyword:
var anArray = new Array();
var anArray = new Array(5);
var anArray = new Array('soccer', 'basketball', …, 'badminton');
This code example shows an Array object being instantiated and demonstrating the three
available constructors. The first line creates an empty Array object without a default size. The
second line creates an Array object with a default size. Each value in the array is undefined
because nothing is assigned to it yet. The last example creates an array initialized with data. In
addition to the object constructors, you can create an array as follows:
var anArray = ['soccer', 'basketball', …,'badminton'];
Under the hood, JavaScript converts the anArray variable to the Array object type. After
creating an array, you can access its elements by using square brackets following the variable
name, as shown in this example:
var anArray = new Array(5);
anArray[1] = 'soccer';
You access elements within an array by their indexed position. This example accesses the
element at index position 1 and assigns a value to it. Arrays in JavaScript are zero-based ,
which means that the first element in the array is at index zero, not at index one. The last
element is at index Array.length -1 —in the preceding example, 5-1=4. Hence, the array
element indexes are 0, 1, 2, 3, and 4.
Sizing arrays is very dynamic. In the preceding example, even though the array is initially
declared to have a length of 5, if you try to access the 10th element, the array automatically
resizes to accommodate the requested length. The following example demonstrates this
var anArray = new Array(5);
anArray[9] = 'soccer';
A multi-dimensional array can contain other arrays. The following code demonstrates this:
var multiArray = new Array(3);
multiArray[0] = new Array(3);
multiArray[1] = new Array(3);
multiArray[2] = new Array(3);
Search WWH ::

Custom Search