Java Reference
In-Depth Information
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 follow-
ing example:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 5: Example 3</title>
</head>
<body>
<script type=”text/javascript”>
var myShopping = new Array(“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();
myShopping.reverse();
document.write(myShopping.join(“<br />”));
}
else
{
document.write(“That is not a valid input”);
}
</script>
</body>
</html>
Save the example as ch5_examp3.htm. When you load this into your browser, you will be asked to
enter some input depending on whether you want the array to be ordered in forward or backward
order. If you enter 1, the array will be displayed in forward order. If you enter -1, the array will be dis-
played in reverse order. If you enter neither of these values, you will be told that your input was invalid.
At the top of the script block, you defi ne the array containing your shopping list. Next you defi ne the
variable ord to be the value entered by the user in a prompt box.
var ord = prompt(“Enter 1 for alphabetical order, and -1 for reverse order”, 1);
This value is used in the conditions of the if statements that follow. The fi rst if checks whether the
value of ord is 1 — that is, whether the user wants the array in alphabetical order. If so, the following
code is executed:
myShopping.sort();
document.write(myShopping.join(“<br>”));
Search WWH ::




Custom Search