An array is a collection of things. An array is a data type that contains or stores numbered pieces of data. Its like a bunch of variables with a collective name. Each numbered slot is called an element of the array, and the number assigned to an element is called its index. The first index is 0 (not 1).
Here is an example of how to create an array of integers and how to get and set the values.
function tryit() { var myarray = new Array(); // create a new empty array var str = new String(); // new empty string to hold results // loop 4 times set each array element to 10 + the loop index for(i=0; i< 3; i++) myarray[i]=10 + i; // concatenate the array elements into the string for(i=0; i< 3; i++) str += myarray[i] + "\n"; alert(str); } // tryit |
<form> <input type="button" value="Run" onClick="tryit();"> </input> </form> |
An element of an array may be of any type, and different elements of the same array may be of different types. Array elements may also be functions, objects, or other arrays.
Arrays are created with the Array() constructor:
var a = new Array(); // creates an empty array with no elements // this next one creates an array with 6 elements, 5 numbers and a string var a = new Array(5, 4, 3, 2, 1, "testing, testing"); var a = new Array(10); // create an empty array with 10 slots
Reading and writing array elements
value = a[0]; // copy value in first array slot to variable value a[1] = 3.14; // set second array slot to pi i = 2; // set up a variable to use later a[i] = 3; // since i is 2, set third slot to 3 a[i+1] = "hello"; // since i is 2, set fourth slot to "hello" // first, i is 2 so the a[i] part evaluates to 3 // then this turns into a[3] = a[0]; // so this sets the fourth element to the // same value as the first element a[a[i]] = a[0];
Array elements can be added on the fly. To add a new element to an array, simply assign a value to it.
var a = new Array() // a is an empty array a[0] = 10; // a contains one element a[9] = "the ninth"; // a contains 10 elements, 8 are undefined a[10000] = "this is element 10,000";
All arrays have a length property that specifies how many elements the array contains (including undefined elements).
var a = new Array(); // a.length == 0 a = new Array(10); // a.length == 10 (empty elements 0-9 defined) a = new Array(1,2,3); // a.length == 3 (elements 0-2 defined) a = [4,5]; // a.length == 2 (elements 0 and 1 defined); a[5] = -1; // a.length = 6 (elements 0, 1, and 5 defined) a[49] = 12; // a.length == 50 (elements 0, 1, 5, and 49 defined)The length property is a read/write value.
a = new Array(10,20,30,40,50); // a.length == 5 a.length = 3; // the 4th and 5th elements are discarded a.length = 10; // elements 4-9 are there but undefined.