3.6 ArraysAn array is a collection of data values, just as an object is. While each data value contained in an object has a name, each data value in an array has a number, or index. In JavaScript, you retrieve a value from an array by enclosing an index within square brackets after the array name. For example, if an array is named a, and i is a non-negative integer, a[i] is an element of the array. Array indexes begin with zero. Thus, a[2] refers to the third element of the array a. Arrays may contain any type of JavaScript data, including references to other arrays or to objects or functions. For example: document.images[1].width This code refers to the width property of an object stored in the second element of an array stored in the images property of the document object. Note that the arrays described here differ from the associative arrays described in Section 3.5. The regular arrays we are discussing here are indexed by non-negative integers. Associative arrays are indexed by strings. Also note that JavaScript does not support multidimensional arrays, except as arrays of arrays. Finally, because JavaScript is an untyped language, the elements of an array do not all need to be of the same type, as they do in typed languages like Java. We'll learn more about arrays in Chapter 9. 3.6.1 Creating ArraysArrays can be created with the Array( ) constructor function. Once created, any number of indexed elements can easily be assigned to the array: var a = new Array( ); a[0] = 1.2; a[1] = "JavaScript"; a[2] = true; a[3] = { x:1, y:3 }; Arrays can also be initialized by passing array elements to the Array( ) constructor. Thus, the previous array-creation and -initialization code could also be written: var a = new Array(1.2, "JavaScript", true, { x:1, y:3 }); If you pass only a single number to the Array( ) constructor, it specifies the length of the array. Thus: var a = new Array(10); creates a new array with 10 undefined elements. 3.6.2 Array LiteralsECMAScript v3 defines (and JavaScript 1.2 implements) a literal syntax for creating and initializing arrays. An array literal (or array initializer) is a comma-separated list of values contained within square brackets. The values within the brackets are assigned sequentially to array indexes starting with zero.[4] For example, in JavaScript 1.2 the array creation and initialization code in the previous section could also be written as:
var a = [1.2, "JavaScript", true, { x:1, y:3 }]; Like object literals, array literals can be nested: var matrix = [[1,2,3], [4,5,6], [7,8,9]]; Also, as with object literals, the elements in array literals can be arbitrary expressions and need not be restricted to constants: var base = 1024; var table = [base, base+1, base+2, base+3]; Undefined elements can be included in an array literal by simply omitting a value between commas. For example, the following array contains five elements, including three undefined elements: var sparseArray = [1,,,,5]; |