Java Reference
In-Depth Information
Array Objects
You saw how to create and use arrays in Chapter 2, and this chapter mentioned earlier that they are
actually objects.
In addition to storing data, Array objects provide a number of useful properties and methods you can
use to manipulate the data in the array and fi nd out information such as the size of the array.
Again, this is not an exhaustive look at every property and method of Array objects but rather just
some of the more useful ones.
This topic uses constructor syntax when creating arrays: var myArray = new Array() . But it's
possible to create arrays with much shorter syntax: var myArray = [] . Simply use the opening and
closing square brackets instead of new Array() . Your authors will continue to use the constructor, for
clarity's sake, throughout the topic.
Finding Out How Many Elements Are in an Array — The length Property
The length property gives you the number of elements within an array, which you have already seen in
the trivia quiz in Chapter 3. Sometimes you know exactly how long the array is, but there are situations
where you may have been adding new elements to an array with no easy way of keeping track of how
many have been added.
The length property can be used to fi nd the index of the last element in the array. This is illustrated in
the following example:
var names = new Array();
names[0] = “Paul”;
names[1] = “Jeremy”;
names[11] = “Nick”;
document.write(“The last name is “ + names[names.length - 1]);
Note that you have inserted data in the elements with index positions 0 , 1 , and 11 . The array index
starts at 0 , so the last element is at index length - 1 , which is 11 , rather than the value of the
length property, which is 12 .
Another situation in which the length property proves useful is where a JavaScript method returns
an array it has built itself. For example, in Chapter 9, on advanced string handling, you'll see that the
String object has the split() method, which splits text into pieces and passes back the result as an
Array object. Because JavaScript created the array, there is no way for you to know, without the length
property, what the index is of the last element in the array.
Joining Arrays — The concat() Method
If you want to take two separate arrays and join them together into one big array, you can use the Array
object's concat() method. The concat() method returns a new array, which is the combination of the
two arrays: the elements of the fi rst array, then the elements of the second array. To do this, you use the
method on your fi rst array and pass the name of the second array as its parameter.
Search WWH ::




Custom Search