Section L. Arrays


L. Arrays

Associative arrays use strings to access the data they hold, for instance test['a']. Real arrays use index numbers for this job, for instance test[0].

An array is nothing more than a collection of values that are indexed numerically. Let's take a look at an array from XMLHTTP Speed Meter. Note that the index numbers of an array start at 0, and not at 1:

[XMLHTTP Speed Meter, lines 4-9]

var speedText = new Array(); speedText[0] = '0' speedText[4] = 'till 4 Mbit/s'; speedText[8] = '4-8 Mbit/s'; speedText[15] = '8-15 Mbit/s'; speedText[20] = '12-20 Mbit/s'; 


Secretly I use this array as an associative array. When the script asks for a download speed, one of the values 0, 4, 8, 15, or 20 is returned. The speedText array defines the bit of text that should be shown next to the animation, and I really only need texts for 0, 4, 8, 15, and 20. Therefore I define only those elements of the array.

But what about the other elements? Since I did not define them, JavaScript does not create them. This is called a sparse array: an array that contains only those elements that are actually defined.

If I do alert(speedText[11]) I get undefined, just as if 11 is a property that hasn't been defined.

Nested arrays

Array elements can be other arrays, in which case they're called nested (or two-dimensional) arrays:

testArray[5] = new Array(); testArray[5][0] = 'Nested array'; 


If you really want to, you can create three-, four-, or more-dimensional arrays by just repeating the process:

testArray[5][0] = new Array(); testArray[5][0][1] = 'A three-dimensional array element!'; 


Array notations

The speedText array works fine, but its creation is a bit ponderous. There are more elegant ways to create an array:

var testArray = new Array(0,1,'2','three',false); // hardly used var testArray = [0,1,'2','three',false]; // array literal 


The first notation is hardly used any more, though you'll occasionally encounter it in older scripts. The second notation is called an array literal, and as you see the syntax is quite close to the object literal, except that we use square brackets [] to enclose the entire array, and we don't use property namesafter all, the arrays use index numbers.

Note that these notations don't give you the option of assigning the elements to specific indices: testArray now has five elements, numbered from testArray[0] to testArray[4]. If you want to define specific indices, you must use the notation we saw in the speedText example.

The findPos() function in Edit Style Sheet returns an array literal:

[Edit Style Sheet, lines 181-191, condensed]

function findPos(obj) {     // calculate curleft and curtop     return [curleft,curtop]; } 


Of course, the function that findPos() returns this array to has to be ready for it:

[Edit Style Sheet, lines 140-141]

var coors = findPos(this); colorPicker.style.top = coors[1] - 20 + 'px'; 


coors now becomes an array, and in the next line the function uses its second element (with index 1): the curtop from the function.

Use of arrays

A few JavaScript methods, notably string.split(), return arrays. Take this example from Form Validation:

[Form Validation, lines 80-85, condensed]

var req = els[i].getAttribute('validation'); var reqs = req.split(' '); for (var j=0;j<reqs.length;j++) {     // go through array elements one by one } 


The split() method of a string always returns an array, so reqs automatically becomes one. The for loop that's started up afterwards goes through the array elements one by one and does something to them.

Arrays and nodeLists

The example scripts contain a few more arrays, but most of them are meant to shore up the deliberate weaknesses of a data type that superficially resembles the array but is in fact quite different: the W3C DOM nodeList.

Take this bit of code:

var x = document.getElementsByTagName('p'); var y = x[2]; 


x is a nodeList that holds references to all <p> tags in the document, and just as in arrays, x[2] means the third element of array x, or the third paragraph in the document. I use this feature of the nodeList regularly.

Nonetheless, nodeLists are not arrays. For now it's best to see them as read-only arrays that lack all useful methods that the Array object defines. In 8I we'll see that, though nodeLists appear to be rather static and boring from an array perspective, they are in fact highly, even dangerously, dynamic.

length

Every array has a length property that holds the number of elements in the array. Let's return to our test array:

var testArray = [0,1,'2','three',false]; alert(testArray.length); 


As you'd expect, the alert shows 5. testArray has five elements with index numbers 0, 1, 2, 3, and 4. The length property is automatically updated whenever you add or remove elements to or from the array.

You are even allowed to set the length property:

var testArray = [0,1,'2','three',false]; testArray.length = 0; alert(testArray[1]); 


Now the alert shows undefined, because we just set the length of testArray to 0, which means "Trash all elements." We could also set the length to another value:

var testArray = [0,1,'2','three',false]; testArray.length = 2; alert(testArray[1]); 


Now the alert shows 1. We set the length of testArray to 2, and therefore all elements with index 2 or higher (the third and subsequent elements) are removed from the array. The first two elements (with index 0 and 1) remain untouched.

push, pop, shift, and unshift

There are four methods for quickly adding and removing elements to and from the beginning or the end of an array: push(), pop(), shift(), and unshift().

Figure 5.1. push, pop, shift, and unshift


As you see in the figure, shift and unshift work on the start of an array, and push and pop on the end. The syntax to add elements is as follows:

var x = [new element to be inserted in the array]; testArray.unshift(x); // x is now the first element testArray.push(x); // x is now the last element 


Note that the element to be added is an argument of the push and unshift methods.

Removing elements works slightly differently:

var x = testArray.shift(); var y = testArray.pop(); 


x now holds the first element of the array, and y the last. These two elements are now wholly removed from the array. Note that shift and pop don't accept arguments.

The length property is updated after each of these four operations.

I always use push and shift for my array manipulations, since this gives a First In First Out situation: the first element I put in the array is also the first element that leaves the array when the time comes to process them. In most situations this doesn't matter, but it's useful to have such a standard rule. I advise you to select one addition and one removal method and stick to them.

A few example scripts use shift and push on helper arrays, but I'll defer the practical explanations to 8I, since we first have to discuss nodeLists and find out why we need helper arrays at all.

Explorer 5 doesn't support these four methods. At the end of Usable Forms and Sandwich Picker, you can find the code I use to add support to Explorer 5.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

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