Java Reference
In-Depth Information
JavaScript created the array, there is no way for you to know, without the length property, what the
index is of the last element in the array.
Adding elements—the push() Method
You'll find that Array objects have many useful methods, but you will probably use the push()
method more than any other. Its purpose is simple—add elements to the array—and it lets you do so
without needing to specify an index, like this:
var names = [];
names.push("Jeremy");
names.push("Paul");
Its usage is simple—simply pass the value you want to add to the array, and that value will be
pushed to the end of the array. So in the previous names array, "Jeremy" and "Paul" are in index
positions of 0 and 1 , respectively.
Joining Arrays—the concat() Method
If you want to take two separate arrays and join them into one big array, you can use the Array
object's concat() method. The concat() method returns a new array, which is the combination of
the two arrays: the elements of the first array, then the elements of the second array. To do this, you
use the method on your first array and pass the name of the second array as its parameter.
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
Paul
Jeremy
Nick
value
ages array
element index
0
1
2
value
31
30
31
If you combine them using names.concat(ages) , you will get an array like the one in the following table:
0
1
2
3
4
5
element index
Paul
Jeremy
Nick
31
30
31
value
In the following code, this is exactly what you are doing:
var names = [ "Paul", "Jeremy", "Nick" ];
var ages = [ 31, 30, 31 ];
 
var concatArray = names.concat(ages);
 
Search WWH ::




Custom Search