Java Reference
In-Depth Information
putting Your Array into reverse Order—the reverse() Method
The next method for the Array object is the reverse() method, which, no prizes for guessing,
reverses the order of the array so that the elements at the back are moved to the front. Let's take the
shopping list again as an example:
index
0
1
2
3
4
Egg s
Milk
Potatoes
Cereal
Ba nana
value
If you use the reverse() method
var myShopping = [ "Eggs", "Milk", "Potatoes", "Cereal", "Banana" ];
myShopping.reverse();
you get
IND ex
0
1
2
3
4
value
Banana
Cereal
Potatoes
Milk
Eggs
To prove this, you could write it to the page with the join() method you saw earlier.
var myShoppingList = myShopping.join("<br />")
document.write(myShoppingList);
trY it out Sorting an Array
When used in conjunction with the sort() method, the reverse() method can be used to sort an array
so that its elements appear in reverse alphabetical or numerical order. This is shown in the following
example:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 5, Example 3</title>
</head>
<body>
<script>
var myShopping = ["Eggs", "Milk", "Potatoes", "Cereal", "Banana"];
 
var ord = prompt("Enter 1 for alphabetical order, " +
"and -1 for reverse order", 1);
 
if (ord == 1) {
myShopping.sort();
document.write(myShopping.join("<br />"));
} else if (ord == -1) {
myShopping.sort();
 
Search WWH ::




Custom Search