Java Reference
In-Depth Information
For example, say you have two arrays, names and ages, and separately they look like the following
tables:
names array
Element Index
0
1
2
Va lue
Paul
Jeremy
Nick
ages array
Element Index
0
1
2
Va lue
31
30
31
If you combine them using names.concat(ages), you will get an array like the one in the following
table:
Element Index
0
1
2
3
4
5
Va lue
Paul
Jeremy
Nick
31
30
31
In the following code, this is exactly what you are doing:
var names = new Array(“Paul”,”Jeremy”,”Nick”);
var ages = new Array(31,30,31);
var concatArray = names.concat(ages);
It's also possible to combine two arrays into one but assign the new array to the name of the existing
fi rst 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 fi rst, and the elements from the
names array are concatenated on the end.
Element Index
0
1
2
3
4
5
Va lue
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 fi rst element you want copied
The index of the element marking the end of the portion you are slicing out (optional)
Search WWH ::




Custom Search