Java Reference
In-Depth Information
It's also possible to combine two arrays into one but assign the new array to the name of the existing
first array, using names = names.concat(ages) .
If you were to use ages.concat(names) , what would be the difference? Well, as you can see in the
following table, the difference is that now the ages array elements are first, and the elements from
the names array are concatenated on the end:
element index
0
1
2
3
4
5
value
31
30
31
Paul
Jeremy
Nick
Copying part of an Array—the slice() Method
When you just want to copy a portion of an array, you can use the slice() method. Using the
slice() method, you can slice out a portion of the array and assign it to a new variable name. The
slice() method has two parameters:
The index of the first element you want copied
The index of the element marking the end of the portion you are slicing out (optional)
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
value
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 = [ "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 like the following table:
index
0
1
Sarah
Jeremy
value
The first array, names , is unaffected by the slicing.
 
Search WWH ::




Custom Search