SQL PHP HTML ASP JavaScript articles and free scripts to download
 

Two dimensional JavaScript array

We can create two dimensional arrays in JavaScript. These arrays are different than two dimensional arrays we have used in ASP. To understand two dimensional arrays we will use some examples. First let us try to create some arrays.

var details = new Array();
details[0]=new Array(3);
details[0][0]="Example 1";
details[0][1]="Example 2";
details[0][2]="Example 3";

details[1]=new Array(2);
details[1][0]="Example 4";
details[1][1]="Example 5";

As you have seen we have declared a array and named it as details. Then we have added elements to this array. Now to access the elements we have to address them like this.

document.write(details[0][2]);

This will give the output as Example 3

Displaying elements of two dimensional array

To display the inner elements of first set of array we have to use for loop. Here is an example.

for(i=0; i<=2; i++){
document.write(details[0][i]);
document.write("<br>");
}

This will give the output as

Example 1
Example 2
Example 3

Now we will use two for loops one inside the other to display all the elements. Here is the code.

for(j=0; j<=1; j++){
for(i=0; i<=2; i++){
document.write(details[j][i]);
document.write("<br>");
}}

The output of the above code is here

Example 1
Example 2
Example 3
Example 4
Example 5
undefined

Note the last line saying undefined. This is because we have not added any element to details[1][2]



Further readings
Declaring array in JavaScript
Displaying elements of an array by looping through
join():Displaying elements of an array using join() function
sort():Sorting of elements of an array using function
length:Length property to get the total number of elements in an array
reverse():Reversing the elements of an array
pop():Removeing last element of an array by using pop()
shift():Removeing first element of an array using shift()
push():Adding elements to array using push()
unshift():Adding elements to array using unshift()
splice():Add replace remove elements from an array using splice()
split():Creating array by splitting string variable
toString: To join all elements and create a string
concat: To join two or more arrays to a single array
slice: To return element from an array with starting and ending positions
Two Dimensional Array: Adding and displaying elements


dipesh patel07-07-2010
one very much better learning method
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked


Join Our Email List
Email:  
For Email Newsletters you can trust
Array Functions