We help IT Professionals succeed at work.

Multiple dimension array

yes4me
yes4me asked
on
How do you define a multiple dimension array in Javascript?
Comment
Watch Question

Commented:
myarray = [
   ["name","Bob"],
   ["age","20"]
  ]


hope this helps

nzjonboy
CERTIFIED EXPERT
Top Expert 2005
Commented:
//create the number of items in the first dimension
//make room for each of the items in the second dimension

arrMultiArray = new Array(3)
arrMultiArray [0] = new Array(1)
arrMultiArray [1]= new Array(1)
arrMultiArray [2] = new Array(4)

//Empty(0)
arrMultiArray [0][0] = " "

//First Column(1)
arrMultiArray [1] [0] = "First Item in First Row"

//Second Column(2)
arrMultiArray [2][0] = "First Item in Second Row"
arrMultiArray [2][1] = "Second Item in Second Row"
arrMultiArray [2][2] = "Third Item in Second Row"
arrMultiArray [2][3] = "Fourth Item in Second Row"


//You can get the value back as follows
//This would return "Third Item in Second Row"
strArrayValue = arrMultiArray [2][2]

Commented:
Or like this...

We create an array "banner" of banner ads with info about the URL, IMG and ALT value...

function bannerAd(url, alt, img)
{
   this.url = url;
   this.alt = alt;
   this.img = img;
}

banner = new Array(
 new bannerAd("http://www.amazon.com/free-books.html",
              "Free Books Exchange",
              "http://www.mydomain.com/ads/amazon1.gif"),

 new bannerAd("http://www.amazon.com/cheap-books.html",
              "Cheap Books Exchange",
              "http://www.mydomain.com/ads/amazon2.gif"),

 new bannerAd("http://www.amazon.com/collectors-books.html",
              "Collectors Books Exchange",
              "http://www.mydomain.com/ads/amazon3.gif")
);

Now you can retrieve the info like this...

banner[0].url
banner[0].alt
banner[0].img

Commented:
This way you have the advantage of having all the fields named so you can refer to them by name or index.

Author

Commented:
I like defining my array using new Array()... and since you are the first one to use them, you get the points. But seriously, you guys are all right.


What you have all confirmed me one thing is that there is not a very nice way to define a multidimension array. Here is what I end up with:


<SCRIPT>
multiArray = new Array(3)
for (i=0; i<3; i++)
   multiArray[i] = new Array(4)
for (i=0; i<multiArray.length; i++)
   for (j=0; j<multiArray[0].length; j++)
      multiArray[i][j] = i+"/"+j
for (i=0; i<3; i++)
{
   for (j=0; j<4; j++)
      document.write(i +"/"+ j +": "+ multiArray[i][j] +"<BR>")
   document.write("<BR>")
}
</SCRIPT>

Explore More ContentExplore courses, solutions, and other research materials related to this topic.