Arrays

From Q
(Redirected from Array)
Jump to navigation Jump to search

An array is essentially a list which contains things. For example, this code creates an array containing animals:

var animals = ["cat","dog","penguin"];

Arrays are indexed using [index], where index indicates the position in the array. The first thing in an array has an index of 0, the second 1, etc. The following code, which can be easily run using Table JavaScript and Plot JavaScript, creates a message box which indicates the name of first entry in the array (i.e., cat) and how many things are in the array.

var animals = ["cat","dog","penguin"];
alert(animals[0] + " is the first of " + animals.length + " animals in the array");

Arrays can also be created by adding items one-by-one using .push():

var animals = new Array();
animals.push("cat");
animals.push("dog");
animals.push("penguin");

It is possible to create arrays which contain other arrays. These are sometimes referred to as jagged arrays. For example, the following code creates an array which itself contains arrays of numbers and returns the third value from the second of arrays.

var x = [[1,2,3],[4,5,6],[7,8,9,10]];
alert(x[1][2]);

See also

For Loops

Sorting Arrays