A JavaScript array is an ordered collection of elements selected by one or more indices. As oposed to scalar variables such as numbers and strings, an array is a data structure used to store a variable number of values of different types.
Array values can be other arrays, thus making it possible to create more complex data structures such as multidimensional arrays and trees. An array with a single dimension is often called a vector, whereas a multidimensional array is called a matrix.
Array indices (or keys) may be either integers or strings. However, arrays should not be used as associative arrays. JavaScript arrays are essentially objects, thus setting string keys means setting properties on those objects. Object should be used instead.
JavaScript arrays are declared using the Array object to construct Array instances or by using the literal array syntax:
var array1 = new Array(arrayLength);
Creates an array with an initial length set to the specified value. The value must be specified as an unsigned integer.
var array2 = new Array(element0, element1, ...);
Creates an array with the specified values as its elements.
Arguments are optional in both cases.
Creating an array using the Array constructor may be a bit confusing and there's a slight chance of undesired results. Therefore it is best to avoid it in favor of the more concise literal form:
var array3 = [element0, element1, ...];
The result is the same. JavaScript takes care of converting between array objects and array primitives. As such, the methods of the Array object are available and can be called on array primitives.
Array elements can be referred to by their index using the special square bracket notation. For example:
var fruits = ["apples", "oranges", "grapes"]; fruits[0]; // apples fruits[2]; // grapes fruits[1]; // oranges
Note that the first element has the index 0.
constructorArray objectlengthprototypeThese properties are not inherited by default and are only available with arrays created by regular expression matches.
indexinputconcat(array1 [, array2 [, ...]])every(callback [, object])filter(callback [, contextObject])forEach(callback [, contextObject])join([separator])map(callback [, contextObject])pop()push(element0 [, element1 [, ...]])reduce(callback [, initialValue])reduceRight(callback [, initialValue])reverse()shift()slice(offset [, length])some(callback [, contextObject])sort([compare_function])splice(offset , length [, element1 [, element2 [, ...]]])toString()unshift(element0 [, element1 [, ...]])valueOf()If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.
Copyright © 2010-2011 Dive Into JavaScript