Two dimensional JavaScript array

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]

Displaying elements by using length Property

In above code we used numbers inside for loops because we already know the number of elements present inside array. If we don't know the number of elements present inside array then we can use the array length property inside for loop to display the elements.
for(j=0; j<details.length; j++){

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

}

Example

var my_2d = [
  ['One', 2],
  ['Two', 4],
  ['Three', 6]
];
// display now
for(i = 0; i < my_2d.length; i++)
document.write(my_2d[i][0] + ',' + my_2d[i][1] + '<br>' );
Output
One,2
Two,4
Three,6

Multidimensional array

Using push to add elements to multidimensional array.
<script>
var my_ans = new Array(); // declaring array 
my_ans.push({0:45,1:55,2:65});	
my_ans.push({0:145,1:155,2:165});	
my_ans.push({0:245,1:255,2:265});	

// displaying the array data //

for(i=0;i<3;i++){
 document.write("key : " + i + "  =>value: " + my_ans[i][0] +
 ',' +my_ans[i][1] + ',' +my_ans[i][2] + "<br>");
}
	
</script>
Output is here
key : 0 =>value: 45,55,65
key : 1 =>value: 145,155,165
key : 2 =>value: 245,255,265
DEMO of displaying elements of array using length
Array Reference How to display elements of an Array
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    dipesh patel

    07-07-2010

    one very much better learning method
    pramol

    23-12-2014

    It's going very easy after learning.....

    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer