Section 7.6. Reading and Writing Array Elements


7.6. 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 nonnegative 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 noted earlier, the [] operator can also be used to access named properties of objects.

 my['salary'] *= 2; 

Because arrays are a specialized kind of object, you can define nonnumeric object properties on an array and access those properties using the . or [] syntax.

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; 

7.6.1. 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.

7.6.2. Deleting Array Elements

The delete operator sets an array element to the undefined value, but the element itself continues to exist. To actually delete an element, so that all elements above it are shifted down to lower indexes, you must use an array method. Array.shift() deletes the first element of an array, Array.pop() deletes the last element, and Array.splice() deletes a contiguous range of elements from an array. These functions are described later in this chapter and also in Part III.

7.6.3. 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.

7.6.4. Iterating Through Arrays

Probably the most common use of the length property of an array is to allow you 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 is not the case, you should test that each array element is defined before using it:

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

You can use this same looping syntax to initialize the elements of an array created with the Array() constructor:

 var lookup_table = new Array(1024); for(var i = 0; i < lookup_table.length; i++)     lookup_table[i] = i * 512; 

7.6.5. Truncating and Enlarging Arrays

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.

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 7.7.

7.6.6. 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 in matrix[x] is an array of numbers. To access a particular number within this array, you would write matrix[x][y]. Here is a concrete example that uses a two-dimensional array as a multiplication table:

 // Create a multidimensional array var table = new Array(10);               // 10 rows of the table for(var i = 0; i < table.length; i++)     table[i] = new Array(10);            // Each row has 10 columns // Initialize the array for(var row = 0; row < table.length; row++) {     for(col = 0; col < table[row].length; col++) {         table[row][col] = row*col;     } } // Use the multidimensional array to compute 5*7 var product = table[5][7];  // 35 




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net