Java Reference
In-Depth Information
Just as with string copying with substring(), the start point is included in the copy, but the end point
is not. Again, if you don't include the second parameter, all elements from the start index onward are
copied.
Suppose you have the array names shown in the following table:
Index
0
1
2
3
4
Va lue
Paul
Sarah
Jeremy
Adam
Bob
If you want to create a new array with elements 1 , Sarah , and 2 , Jeremy , you would specify a start
index of 1 and an end index of 3 . The code would look something like this:
var names = new Array(“Paul”,”Sarah”,”Jeremy”,”Adam”,”Bob”);
var slicedArray = names.slice(1,3);
When JavaScript copies the array, it copies the new elements to an array in which they have indexes 0
and 1 , not their old indexes of 1 and 2 .
After slicing, the slicedArray looks the following table:
Index
0
1
Value
Sarah
Jeremy
The fi rst array, names , is unaffected by the slicing.
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
Value
Eggs
Milk
Potatoes
Cereal
Banana
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, so this means you need to use the <br /> tag between each element. First,
you need to declare your array.
var myShopping = new Array(“Eggs”,”Milk”,”Potatoes”,”Cereal”,”Banana”);
Now, convert the array into one string with the join() method.
var myShoppingList = myShopping.join(“<br />”);
Search WWH ::




Custom Search