SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Multi-Dimensional Array

    I have an array, called, "myArray". Inside this myArray are 4 more arrays, "m0, m1, m2, m3".
    How do I access all the elements in all the array?

    Here's my code, :
    Code:
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    
    <body>
    <script>
    var m0 = [0, 1, 2, 3, 4];
    var m1 = [5, 6, 7, 8, 9];
    var m2 = [10, 11, 12, 13, 14];
    var m3 = [15, 16, 17, 18, 19];
    
    var myArray = [m0, m1, m2, m3];
    
    
    for (var i = 0; i < myArray.length; i++) {
        for (var j = 0; j < ("m"+i).length; j++) {
            document.writeln(myArray[i][j]);
        }
    }
    </script>
    </body>
    </html>

    This code only give me the first 2 elements in each array.
    But, I would like to get all the elements in all the arrays.

    tks

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,890
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    The problemn is with this line:

    Code JavaScript:
    for (var j = 0; j < ("m"+i).length; j++) {

    "m"+i will evaluate to a two character string (e.g. "m0", "m1" etc), which will have the length of two (hence only the first two elements being output).

    You can do what you want like this instead:

    Code JavaScript:
    var m0 = [0, 1, 2, 3, 4];
    var m1 = [5, 6, 7, 8, 9];
    var m2 = [10, 11, 12, 13, 14];
    var m3 = [15, 16, 17, 18, 19];
    var myArray = [m0, m1, m2, m3];
     
    for (i = 0; i < myArray.length; i++) {
      console.log('myArray[' + i + '] contains: ');
      for (j = 0; j < myArray[i].length; j++) {
        console.log(myArray[i][j]);
      }
      console.log('\r');
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •