JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

Chapter 9. Arrays

Contents:

Arrays and Array Elements
Array Methods

Chapter 8 documented the JavaScript object type -- a composite data type that holds named values. This chapter documents arrays -- a composite data type that holds numbered values. Note that the arrays we'll discuss in this chapter are different from the associative arrays described in the previous chapter. Associative arrays associate values with strings. The arrays described in this chapter are just regular numeric arrays; they associate values with non-negative integers.

Throughout this book, we often treat objects and arrays as distinct data types. 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. We see this when we use the typeof operator: applied to an array value, it returns the string "object". Note that the extra functionality of arrays was introduced in JavaScript 1.1. Arrays are not supported in JavaScript 1.0.

This chapter documents basic array syntax, array programming techniques, and methods that operate on arrays.

9.1. Arrays and Array Elements

An array is a data type that contains or stores numbered values. Each numbered value is called an element of the array, and the number assigned to an element is called 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.

9.1.1. Creating Arrays

In JavaScript 1.1 and later, arrays are created with the Array( ) constructor and the new operator. You can invoke the Array( ) constructor in three distinct ways.

The first way is to call it with no arguments:

var a = new Array( ); 

This method creates an empty array with no elements.

The second method of invoking the Array( ) constructor allows you to explicitly specify values for the first n elements of an array:

var a = new Array(5, 4, 3, 2, 1, "testing, testing"); 

In this form, the constructor takes a list of arguments. Each argument specifies an element value and may be of any type. Elements are assigned to the array starting with element 0. The length property of the array is set to the number of arguments passed to the constructor.

The third way to invoke the Array( ) constructor is to call it with a single numeric argument, which specifies a length:

var a = new Array(10); 

This technique creates an array with the specified number of elements (each of which has the undefined value) and sets the array's length property to the value specified.[33]

[33]In client-side JavaScript in Netscape, if the language attribute of the <script> tag is explicitly set to "JavaScript1.2", this third form of the Array( ) constructor behaves like the second form: it creates an array of length one and initializes that array element to the constructor argument. This does not conform to the ECMAScript standard.

Finally, array literals provide another way to create arrays. An array literal allows us to embed an array value directly into a JavaScript program in the same way that we define a string literal by placing the string text between quotation marks. To create an array literal, simply place a comma-separated list of values between square brackets. For example:

var primes = [2, 3, 5, 7, 11];
var a = ['a', true, 4.78]; 

Array literals can contain object literals or other array literals:

var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]]; 

Chapter 3 provides complete details on array literals.

9.1.2. Reading and Writing Array Elements

You access an element of an array using the [] operator. A reference to the array should appear to the left of the brackets. An arbitrary expression that has a non-negative integer value should be inside the brackets. You can use this syntax to both read and write the value of an element of an array. Thus, the following are all legal JavaScript statements:

value = a[0];
a[1] = 3.14;
i = 2;
a[i] = 3;
a[i + 1] = "hello";
a[a[i]] = a[0]; 

In some languages, the first element of an array is at index 1. In JavaScript (as in C, C++, and Java), however, the first element of an array is at index 0.

As we saw in Chapter 8, the [] operator can also be used to access named object properties:

my['salary'] *= 2; 

This is a clue that tells us that objects and arrays are fundamentally the same thing.

Note that array indexes must be integers greater than or equal to 0 and less than 232 -1. If you use a number that is too large, a negative number, or a floating-point number (or a boolean, an object, or other value), JavaScript converts it to a string and uses the resulting string as the name of an object property, not as an array index. Thus, the following line creates a new property named "-1.23"; it does not define a new array element:

a[-1.23] = true; 

9.1.3. Adding New Elements to an Array

In languages such as C and Java, an array has a fixed number of elements that must be specified when you create the array. This is not the case in JavaScript -- an array can have any number of elements, and you can change the number of elements at any time.

To add a new element to an array, simply assign a value to it:

a[10] = 10; 

Arrays in JavaScript may be sparse. This means that array indexes need not fall into a contiguous range of numbers; a JavaScript implementation may allocate memory only for those array elements that are actually stored in the array. Thus, when you execute the following lines of code, the JavaScript interpreter will typically allocate memory only for array indexes 0 and 10,000, not for the 9,999 indexes between:

a[0] = 1;
a[10000] = "this is element 10,000"; 

Note that array elements can also be added to objects:

var c = new Circle(1,2,3);
c[0] = "this is an array element of an object!" 

This example merely defines a new object property named "0", however. Adding array elements to an object does not make it an array. Arrays created with the Array( ) constructor or an array literal have some special features, explained below, that objects do not share.

9.1.4. Array Length

All arrays, whether created with the Array( ) constructor or defined with an array literal, have a special length property that specifies how many elements the array contains. More precisely, since arrays can have undefined elements, the length property is always one larger than the largest element number in the array. Unlike regular object properties, the length property of an array is automatically updated to maintain this invariant when new elements are added to the array. The following code illustrates:

var a = new Array( );   // a.length == 0  (no elements defined)
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] = 0;             // a.length == 50 (elements 0, 1, 5, and 49 defined) 

Remember that array indexes must be less than 232 -1, which means that the largest possible value for the length property is 232 -1.

Probably the most common use of the length property of an array is to allow us to loop through the elements of an array:

var fruits = ["mango", "banana", "cherry", "pear"];
for(var i = 0; i < fruits.length; i++)
    alert(fruits[i]); 

This example assumes, of course, that elements of the array are contiguous and begin at element 0. If this were not the case, we would want to test that each array element was defined before using it:

for(var i = 0; i < fruits.length; i++)
    if (fruits[i] != undefined) alert(fruits[i]); 

The length property of an array is a read/write value. If you set length to a value smaller than its current value, the array is truncated to the new length; any elements that no longer fit are discarded and their values are lost. If you make length larger than its current value, new, undefined elements are added at the end of the array to increase it to the newly specified size.

Truncating an array by setting its length property is the only way that you can actually shorten an array. If you use the delete operator to delete an array element, that element becomes undefined, but the length property does not change.

Note that although objects can be assigned array elements, they do not have a length property. The length property, with its special behavior, is the most important feature of arrays. The other features that make arrays different from objects are the various methods defined by the Array class, which are described in Section 9.2.

9.1.5. Multidimensional Arrays

JavaScript does not support true multidimensional arrays, but it does allow you to approximate them quite nicely with arrays of arrays. To access a data element in an array of arrays, simply use the [] operator twice. For example, suppose the variable matrix is an array of arrays of numbers. Every element matrix[x] is an array of numbers. To access a particular number within this array, you would write matrix[x][y].



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.