The Array
object provides a means of storing and handling a set of other objects. Arrays can store numbers, strings, or other JavaScript objects. There are a couple different ways to create JavaScript arrays. For example, the following statements create three identical versions of the same array:
var arr = ["one", "two", "three"];
var arr2 = new Array();
arr2[0] = "one";
arr2[1] = "two";
arr3[2] = "three";
var arr3 = new Array();
arr3.push("one");
arr3.push("two");
arr3.push("three");
The first method defines arr
and sets the contents in a single statement, using []
. The second method creates the arr2
object and then adds items to it, using direct index assignment. The third method creates the arr3
object and then uses the best option for extending arrays: It uses the push()
method to push items onto the array.
To determine the number of elements in an array, you can use the length
property of the Array
object, as in this example:
var numOfItems = arr.length;
Arrays follow a zero-based index, meaning that the first item is at index 0 and so on. For example, in the following code, the value of variable first
will be Monday
, and the value of variable last
will be Friday
:
var
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
var first = w [0];
var last = week[week.length-1];
The Array
object has several built-in functions that allow you to access and manipulate arrays in various ways. Table 2.7 describes the methods attached to the Array
object that allow you to manipulate the array contents.
To get you started using the functionality provided in the Array
object, the following sections describe some of the common tasks that can be done using Array
object methods.