Java Reference
In-Depth Information
The array is sorted and then displayed to the user on separate lines using the join() method. Next, in
the else if statement, you check whether the value of ord is -1 — that is, whether the user wants the
array in reverse alphabetical order. If so, the following code is executed:
myShopping.sort();
myShopping.reverse();
document.write(myShopping.join(“<br />”));
Here, you sort the array before reversing its order. Again the array is displayed to the user by means of
the join() method.
Finally, if ord has neither the value 1 nor the value -1, you tell the user that his input was invalid.
document.write(“That is not a valid input”);
New Array Methods
In 2005, Mozilla updated the JavaScript engine in Firefox. In doing so, they added seven new methods
to the Array object. These seven methods can be divided into two categories: location methods and
iterative methods.
The following seven methods do not work Internet Explorer. They do, however, work in Firefox, Safari,
Opera, and Chrome.
Finding Array Elements — The indexOf() and lastIndexOf() Methods
As you can probably guess by their names, these two methods resemble the functionality of the String
object's indexOf() and lastIndexOf() methods — they return the index of an item's fi rst and last
occurrence in an array. Consider the following code:
var colors = new Array(“red”, ”blue”, “green”, “blue”);
alert(colors.indexOf(“red”));
alert(colors.lastIndexOf(“blue”));
The fi rst line of code creates an array called colors. It has four elements (two of which are blue). The
second line alerts 0 to the user, as red is the fi rst element of the array.
Remember the String object's lastIndexOf() method searches the array backwards and returns the
index of the fi rst matching character. The lastIndexOf() method of the Array object behaves similarly,
so the third line shows the user the value of 3.
Also similar to the String object's methods of the same name, these two methods return a value of -1
if the element could not be found in the array.
Iterating Through an Array Without Loops
The remaining fi ve methods are called iterative methods because they iterate, or loop, through the array.
In addition, these methods execute a function you defi ne on every element while they iterate through the
Search WWH ::




Custom Search