Java Reference
In-Depth Information
myShopping.reverse();
document.write(myShopping.join("<br />"));
} else {
document.write("That is not a valid input");
}
</script>
</body>
</html>
Save the example as
ch5 _ example3.html
. 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 displayed 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 define the array containing your shopping list. Next you define 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 first
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 />"));
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");
Finding Array elements—the indexOf() and lastIndexOf() Methods
As you can probably guess, the
Array
object's
indexOf()
and
lastIndexOf()
methods behave
similarly to the
String
object's methods—they return the index of an item's first and last occurrence
in an array. Consider the following code:
var colors = [ "red", "blue", "green", "blue" ];
alert(colors.indexOf("red"));
alert(colors.lastIndexOf("blue"));