Arrays are ordered collections of values referred to by a single variable name. For instance, if you have an array named student, you might have the following ordered values:
student[0] = "Bob"
student[1] = 10
student[2] = 75
Array elements are referred to by their indexes-the numbers in brackets. In JavaScript, arrays start with index zero.
Arrays in JavaScript are created using the Array() constructor object. You can create an array of undefined length by using the r">new keyword:
arrayName = new Array();
The length of the array changes dynamically as you assign values to the array. The length of the array is defined by the largest index number used.
For instance
var sampleArray = new Array();
sampleArray[49] = "50th Element";
creates an array with 50 elements. (Remember, indexes start at zero.)
It is also possible to define an initial length of an array by passing the length to the Array() object as an argument:
var sampleArray = new Array(100);
In addition, you can create an array and assign values to all its elements at the time it is defined. This is done by passing the value for all elements as arguments to the Array() object. For instance,
var sampleArray = new Array("1st Element", 2, "3rd Element);
creates a three-element array with the values
sampleArray[0] == "1st Element"
sampleArray[1] == 2
sampleArray[2] == "3rd Element"
As objects, arrays have several methods, including
* join() returns all elements of the array joined together as a single string. This takes one argument: a string used as the separator between each element of the array in the final string. If the argument is omitted, join() uses a comma-space as the separator.
* reverse() reverses the order of elements in the array.
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. Inside the brackets should appear an arbitrary expression that has a non-negative integer value. 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:
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 well as C, C++, and Java, however, the first element of an array is at index 0.[1]
Adding New Elements to an Array
In languages like C and Java, arrays have a fixed number of elements that must be specified when you create the array. This is not the case in JavaScript--arrays 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 are sparse. This means that array indexes need not fall into a contiguous range of numbers, and that memory is allocated only for those array elements that are actually stored in the array. Thus, when you execute the following lines of code, JavaScript allocates 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";
Removing Elements from an Array
Once an element of an array has been defined, you can set its value to null or anything else, but there is no way to actually undefine that element, short of actually truncating the array, which (as we'll see later in the chapter) is possible in Navigator 3.0.
The Select.options[] array is an exception to this rule. It represents HTML elements in client-side JavaScript and has special behavior in Navigator 3.0, including the ability to delete individual elements. See the entry in the reference section of this book for more.
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].
Instead of using arrays of arrays, you can also use associative arrays to simulate multidimensional arrays. Because an associative array allows an arbitrary string as its index, it is easy to use them to simulate multidimensional arrays--i.e., to look up a value based on more than one index. You could use the following function, for example, to simulate reading a value from a three-dimensional array:
Array Length Property
As we saw in the previous section, the Array() constructor method automatically initializes a length property for the array you create. When you create an array with this constructor (available only in Navigator 3.0 and later) this length property is automatically updated by JavaScript so that it is always one greater than the largest element number in the array. The following code illustrates this:
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[5] = -1; // a.length == 6 (elements 0,1,2, and 5 defined)
a[49] = 0; // a.length == 50 (elements 0,1,2,5, and 49 defined)
The length property of a Navigator 3.0 array is not read-only. You can set length to a value smaller than its current value; the array will then be shortened to the new length--elements will be truncated from the end of the array, and their values will be lost. If you change the length property so that it is larger than its current value, the array will be made larger--new, undefined, elements will be added at the end to increase it to the newly specified size.
We've said that arrays are the same data type as objects are, and that any object can have array elements. This is true, but in Navigator 3.0, arrays created with the Array() constructor have features that other objects do not have. One of these features is the length property. If you create an object with the Object() constructor (or a constructor you define yourself) you can assign array elements to that object, but that object will not have the special length property described in this section.
Because the Array() constructor and the array length property are not available in Navigator 2.0, JavaScript programs written for Navigator 2.0 often define custom array constructor functions that attempt to simulate the length property. (To avoid confusion with the "real" length property of arrays in 3.0, I prefer to name the property size in 2.0.) We saw such an array constructor in Example 8.1, and will learn more about arrays in Navigator 2.0 later in this chapter.
function index3(arr, x, y, z)
{
return arr[x + "," + y + "," + z];
}
This example works because it combines the x, y, and z index values into a single, unique string that acts as a property name in the associative array (or object).
Array Methods
In the previous section we saw that--in Navigator 3.0 and Internet Explorer 3.0--arrays created with the Array() constructor have a length property. In Navigator 3.0, but not in IE 3.0, these arrays also support three methods that can be used to manipulate the array elements. These methods will be implemented in a future version of IE.
The Array.join() method converts all the elements of the array to a string, and concatenates them, separating them with an optionally specified string passed as an argument to the method. If no separator string is specified, then a comma is used. For example, the following lines of code produce the string "1,2,3":
a = new Array(1,2,3); // Create a new array with these three elements.
s = a.join(); // s == "1,2,3"
And the following lines specify the optional separator to produce a slightly different result:
a = new Array(1,2,3);
s = a.join(", "); // s == "1, 2, 3". Note the space after the comma.
In some ways, the Array.join() method is the reverse of the String.split() method which creates an array by breaking a string up into pieces.
The Array.reverse() method reverses the order of the elements of an array. It does this "in place"--i.e., it doesn't create a new array with the elements rearranged, but instead rearranges them in the already existing array. For example, the following code, which uses the reverse() and the join() methods, produces the string "3,2,1":
a = new Array(1,2,3); // a[0] = 1; a[1] = 2; a[2] = 3;
a.reverse(); // now a[0] = 3; a[1] = 2; a[2] = 1;
s = a.join() // s = "3,2,1"
The final array method is Array.sort(), which sorts the elements of an array. Like the reverse() method, it does this "in place". When sort() is called with no arguments, it sorts the array elements in alphabetical order (temporarily converting them to strings, to perform the comparison, if necessary):
a = new Array("banana", "cherry", "apple");
a.sort();
s = a.join(", "); // s == "apple, banana, cherry".
You can also pass an argument to the sort() method if you want to sort the array elements in some other order. To allow this method to be a fully general sorting algorithm, the optional argument should be a function. This function will be passed two arguments that it should compare. If the first argument should appear before the second in the sorted array, then the function should return a number less than zero. If the first argument should appear after the second in the sorted array, then the function should return a number greater than zero. And if the two values are equivalent (their order is irrelevant), then the function should return 0. So, for example, to sort array elements into numerical, rather than alphabetical order, you might do the following:
a = new Array(33, 4, 1111, 222);
a.sort(); // alphabetical order: 1111, 222, 33, 4
function numberorder(a,b) {
return a-b;
}
a.sort(numberorder); // numerical order: 4, 33, 222, 1111
You can probably think of other comparison functions that will sort numbers into various esoteric orders: reverse numerical order, odd numbers before even numbers, etc. The possibilities become more interesting, of course, when the elements you are comparing are objects rather than simple types like numbers or strings.
concat Method
The concat method joins two or more Array objects producing one new one. The original Array objects are unaffected by this but, if one copy of a string or number is altered, it is not reflected in the other, whereas a change to an object reference can be seen in both copies.
Syntax: Array.concat(arrayName2, arrayName3, ..., arrayNameN)
pop Method Netscape Only Feature
The pop method is used to remove and return the last element of an array. This affects the length of the array.
Syntax: Array.pop()
push MethodNetscape Only Feature
The push method is used to add one or more elements to an array, returning the new length of it. This affects the length of the array.
Syntax: Array.push(element1, ..., elementN)
reverse Method
The reverse method, as the name implies, reverses the order of the elements in an array making the first last and the last first. Syntax: Array.reverse()
shift Method Netscape Only Feature
The shift method removes and returns the first element of an array. This affects the length of the array.
Syntax: Array.shift()
slice MethodNetscape Only Feature
The slice method creates a new array from a selected section of an array.
Syntax: Array.slice(begin[,end])
splice MethodNetscape Only Feature
The splice method is used to add and/or remove elements of an array.
Syntax; Array.splice(index, howMany, [element1][, ..., elementN])
toSource Method Netscape Only Feature
The toSource method is inherited from the Object object and returns the source code of the array. For details see the Object.toSource method.
Syntax: Array.toSource()
toString Method
The toString method is inherited from the Object object and returns a string representing the specified array and its elements. For more details see the Object.toString method.
Syntax: Array.toString()
unshift Method Netscape Only Feature
The unshift method adds one or more elements to the beginning of an array and returns the new length.
Syntax: Array.unshift(element1,..., elementN)
valueOf Method
The valueOf method is inherited from the Object object and returns a primitive value for a specified array. For details see the Object.valueOf method.
Syntax: Array.valueOf()
Array Summary
JavaScript array creation, usage, and compatibility techniques can be confusing. Here are the main points of this chapter in review:
* Arrays and objects are the same thing in JavaScript. Any object can have array elements, and any array can have object properties.
* In Navigator 3.0, there are three methods that can be used to manipulate arrays:
1. You can can convert an array, and all of its elements into a single string with the Array.join() method.
2. You can reverse the order of elements in an array with the Array.reverse() method.
3. You can sort the elements of an array with the Array.sort() method.
* In Navigator 3.0 and Internet Explorer 3.0, array elements and object properties do not overlap and cannot overwrite each other. There is an Array() constructor, and arrays created with this constructor have a (read-only in IE 3.0) length property that is automatically maintained so that it always contains a value one greater than the largest index of the array.
* In Navigator 2.0, object properties and array elements overlap; when you create a new property, it is as if you added a new array element one higher than the highest existing element. There is no built-in Array() constructor, but you can write your own. Also, there is no automatically maintained length property, but it is common to reserve element 0 of an array for a size property (which you update yourself as the array grows).
* For many algorithms, the size of an array is maintained in a variable externally to an array, and there is no need for a length or size property.
* All arrays in JavaScript are implemented as associative arrays, and can be "sparse"--i.e., they can contain non-contiguous elements. Usually, though, you'll use arrays as if they were non-associative, fixed-size arrays like those found in C, C++, and Java.
0 comments
Post a Comment