Using the Java Script Array Object
Mutidimensional Arrays
In the previous example, the data for two employees was simply placed sequentially
in the array. The data could have been made easier to access by creating a mutidimensional
array, which is an array of arrays. The code below creates an array of arrays containing
employee data.
var employee = [
["Jim Shoe",5,18.45],
["Bob Sled",2,45.90]];
for(var i = 0; i < employee.length; i++)
{
document.write("Name: " + employee[i][0] + "<br />");
document.write("Years: " + employee[i][1] + "<br />");
document.write("Pay Rate: " + employee[i][2] + "<br /><br />");
}
Note how each array element is accessed using two array indexes.
Output:
Name: Jim Shoe
Years: 5
Pay Rate: 18.45
Name: Bob Sled
Years: 2
Pay Rate: 45.9
Array Object Methods
array.concat
The concat method allows you to join two arrays into a new array. The code below
creates an array named char, initializing it with the characters a, b, and c, and
it creates an array named digit , initializing it with the integers 1, 2, and 3.
The concat method is then used to join the two array into an array named both.
var char = ['a', 'b' ,'c'];
var digit = [1, 2 ,3];
var both = char.concat(digit);
for(var i = 0; i < both.length; i++)
document.write(both[i]);
Output:
abc123
The both array contains the values a, b, c, 1, 2, 3.
array.join
The join method allows you to define a string of one or more characters that
will act as a separator between the array's elements. The code below creates an array
named employee, initializing it with three fictitious employee names. The join
method is then used to set the html line break tag as a separator between the array's elements.
var employee = new Array(3);
employee[0] = "Jim Shoe";
employee[1] = "Bob Sled";
employee[2] = "Dugg Graves";
arrOut = employee.join("<br />");
document.write(arrOut);
Output:
Jim Shoe
Bob Sled
Dugg Graves
Setting the separator to the break tag allows the array elements to automatically be
displayed in a column format.
|