7.5. ArraysAn array is an ordered collection of values. Each value is called an element, and each element has a numeric position in the array, known as its index. Because JavaScript is an untyped language, 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 even contain other arrays, which allows you to create data structures that are arrays of arrays. Throughout this book, objects and arrays are often treated as distinct datatypes. This is a useful and reasonable simplification; you can treat objects and arrays as separate types for most of your JavaScript programming. To fully understand the behavior of objects and arrays, however, you have to know the truth: an array is nothing more than an object with a thin layer of extra functionality. You can see this with the typeof operator: applied to an array value, it returns the string "object". The easiest way to create an array is with an array literal, which is simply a comma-separated list of array elements within square brackets. For example: var empty = []; // An array with no elements var primes = [2, 3, 5, 7, 11]; // An array with 5 numeric elements var misc = [ 1.1, true, "a", ]; // 3 elements of various types The values in an array literal need not be constants; they may be arbitrary expressions: var base = 1024; var table = [base, base+1, base+2, base+3]; Array literals can contain object literals or other array literals: var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]]; The first value in an array literal is stored at index 0 of the newly created array. The second value is stored at index 1, and so on. Undefined elements are created by simply omitting the element value between commas: var count = [1,,3]; // An array with 3 elements, the middle one undefined. var undefs = [,,]; // An array with 2 elements, both undefined. Another way to create an array is with the Array() constructor. You can invoke this constructor in three distinct ways:
|