Java Reference
In-Depth Information
Converting an Array into a Single String—the join() Method
The join() method concatenates all the elements in an array and returns them as a string. It
also enables you to specify any characters you want to insert between elements as they are joined
together. The method has only one parameter, and that's the string you want between elements.
An example will help explain things. Imagine that you have your weekly shopping list stored in an
array, which looks something like this:
index
0
1
2
3
4
Eggs
Milk
Potatoes
Cereal
Banana
value
Now you want to write out your shopping list to the page using document.write() . You want each
item to be on a different line, and you can do this by using the <br /> tag between each element
in the array. The <br/> tag is an HTML line break, a visual carriage return for breaking text into
different lines. First, you need to declare your array:
var myShopping = [ "Eggs", "Milk", "Potatoes", "Cereal", "Banana" ];
Next, convert the array into one string with the join() method:
var myShoppingList = myShopping.join("<br />");
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.
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 define 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 = [ "Paul", "Sarah", "Jeremy", "Adam", "Bob" ];
 
names.sort();
 
document.write("Now the names again in order <br />");
 
for (var index = 0; index < names.length; index++) {
document.write(names[index] + "<br />");
}
 
Search WWH ::




Custom Search