Java Reference
In-Depth Information
Now the variable myShoppingList will hold the following text:
“Eggs<br />Milk<br />Potatoes<br />Cereal<br />Banana”
which you can write out to the page with document.write().
document.write(myShoppingList);
The shopping list will appear in the page with each item on a new line, as shown in Figure 5-1.
Figure 5-1
Putting Your Array in Order — The sort() Method
If you have an array that contains similar data, such as a list of names or a list of ages, you may want
to put them in alphabetical or numerical order. This is something that the sort() method makes very
easy. In the following code, you defi ne your array and then put it in ascending alphabetical order using
names.sort() . Finally, you output it so that you can see that it's in order.
var names = new Array(“Paul”,”Sarah”,”Jeremy”,”Adam”,”Bob”);
var elementIndex;
names.sort();
document.write(“Now the names again in order” + “<br />”);
for (elementIndex = 0; elementIndex < names.length; elementIndex++)
{
document.write(names[elementIndex] + “<br />”);
}
Don't forget that the sorting is case sensitive, so Paul will come before paul . Remember that JavaScript
stores letters encoded in their equivalent Unicode number, and that sorting is done based on Unicode
Search WWH ::




Custom Search