Results 1 to 5 of 5

Thread: What's proper syntax to create multi arrays

  1. #1
    Join Date
    Apr 2009
    Location
    Sydney, Australia
    Posts
    118
    Thanks
    16
    Thanked 1 Time in 1 Post

    Default What's proper syntax to create multi arrays

    Hi guys,

    I've been on here several times to seek answers that are rarely answered, so maybe I am punching a bit above my weight division or i should look for an alternative forum for answers.

    This is a simple multidimensional array problem I have, with semantics.

    The issue is that I declare an array as such

    Code:
    var array = new Array([' ', ' ', ' ', ' ', ' ', ' ']);
    which shows up as
    Code:
    array[0][0]
    array[0][1]
    array[0][2]
    array[0][3]
    array[0][4]
    array[0][5]
    etc...

    later in the code I declare again

    Code:
    for(i=0;i<10;i++)
    	  {
    		array[i] = new Array([' ', ' ', ' ', ' ', ' ', ' ']);
    	  }
    This is necessary because I need to create an initial array with a random maximum value so its size is unknown. In the second pass I wish to add variables, and the script works, however, it creates an unnecessary extra node to the array,
    which shows up as
    Code:
    array[0][0][0]
    array[0][0][1]
    array[0][0][2]
    array[0][0][3]
    array[0][0][4]
    array[0][0][5]
    Is there a way to optimize the array to a depth of 2 nodes rather than 3?

  2. #2
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,891
    Thanks
    2
    Thanked 441 Times in 435 Posts

    Default

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <script  type="text/javascript">
    /*<![CDATA[*/
    var array = ['a ', 'b ', 'c ', 'd ', 'e ', 'f '];
    alert(array[1]);
    
    array[1]=[];
     for (var z0=0;z0<4;z0++){
      array[1][z0]=z0;
     }
    alert(array[1]);
    /*]]>*/
    </script>
    </body>
    
    </html>
    or

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <script  type="text/javascript">
    /*<![CDATA[*/
    var array = [[],['b','c'],[],[],[],[]];
    alert(array[1]);
    
     for (var z0=0;z0<4;z0++){
      array[1][z0]=z0;
     }
    alert(array[1]);
    /*]]>*/
    </script>
    </body>
    
    </html>
    Last edited by vwphillips; 12-28-2010 at 05:02 PM. Reason: 2nd example
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    @sniperman

    Part One:

    To answer your question in slightly more general terms, Vic is right when he types in his second example:

    Code:
    var array = [[],['b','c'],[],[],[],[]];
    That's the proper way to create a multidimensional array.

    One could also do it like so:

    Code:
    var array = [];
    array[0] = [];
    array[1] = ['b','c'];
    array[2] = [];
    array[3] = [];
    array[4] = [];
    array[5] = [];
    That makes the same exact array. The reason to avoid the new Array() constructor is that might confuse the script parser later in certain circumstances when making inquiries about the array produced. And it's more expensive visa vis processing time.

    What he then does with it might be a little misleading. He takes the second element (array[1]), which is itself an array:

    Code:
    ['b','c']
    and transforms it into:

    Code:
    [0,1,2,3]
    so the base array (array) now equals:

    Code:
    [[],[0,1,2,3],[],[],[],[]]

    Part Two:

    So let's say you want to make an array with one element that contains an array of six elements, all basically empty like you do here:

    Code:
    var array = new Array([' ', ' ', ' ', ' ', ' ', ' ']);
    That should be:

    Code:
    var array = [[' ', ' ', ' ', ' ', ' ', ' ']];
    but either way var array is a multidimensional array with a length of 1 and array[0] is a simple array with a length of 6, each of its elements is a a string containing one space. This could be expressed as you did like:

    array[0][0]
    array[0][1]
    array[0][2]
    array[0][3]
    array[0][4]
    array[0][5]
    Notice I used no code, it's just a quote because it isn't really code. It does describe the structure of the array, but not the value of any of its contents

    When you then go:

    Code:
    for(i=0;i<10;i++)
    	  {
    		array[i] = new Array([' ', ' ', ' ', ' ', ' ', ' ']);
    	  }
    You are for each of the numbers 0 through 9 making a new multidimensional array and assigning it as a value for each of the elements of the previously declared array (var array). If array[i] exists, it's overwritten. If not, it's created. So you don't only get, and perhaps not at all (in your notation):

    array[0][0][0]
    array[0][0][1]
    array[0][0][2]
    array[0][0][3]
    array[0][0][4]
    array[0][0][5]
    I'd find it hard to describe in any notation what you would have. But suffice it to say that var array now has a length of 10. So if the above notation is correct, you would also have a:

    array[1][0][0]
    array[1][0][1]
    array[1][0][2]
    array[1][0][3]
    array[1][0][4]
    array[1][0][5]
    and so on up to and including 9.

    What you would have is the same as if you started over and just did:

    Code:
    var array = [];
    array[0] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[1] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[2] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[3] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[4] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[5] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[6] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[7] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[8] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    array[9] = [[' ', ' ', ' ', ' ', ' ', ' ']];
    Which kind of brings me back down to earth a bit because you say you don't want any of that. It would be simpler if you used a different name than 'array' for your array, and had some actual values, as well as an actual purpose. Do you have any of that?
    Last edited by jscheuer1; 12-29-2010 at 04:34 PM. Reason: minor correction in description, later add the bit about 'started over'
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  4. The Following User Says Thank You to jscheuer1 For This Useful Post:

    sniperman (12-30-2010)

  5. #4
    Join Date
    Apr 2009
    Location
    Sydney, Australia
    Posts
    118
    Thanks
    16
    Thanked 1 Time in 1 Post

    Default

    Ahhhh, thanks jscheuer1.

    The code example from vwphillips made sense but confused me a little because it made an array then overwrote the array's structure, while my intention is to append one extra element to the length of the multidimensional array.

    var array is a multidimensional array with a length of 1 and array[0] is a simple array with a length of 6, each of its elements is a a string containing one space.
    I attempt to do this by adding an extra layer in the form of a new array.

    The actual code I would rather keep a little confidential because it's part of a game development project I am making... but I will share a concise version here.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript">
    
    
    /*	ENVIRONMENTAL VARIABLES	 */
    var inhabitants;
    var land_plots;
    var total=0;
    
    
    /* GAME VARIABLES 
      land_plots[]
      0 = INHABITANTS
      1 = 
      2 = 
      3 = 
      4 = 
      5 = 
    
    */
    	  var land_plots = new Array([' ', ' ', ' ', ' ', ' ', ' ', ' ']);
    
    /*******************************/
    
    function generateEnvironment()  
     	{
    	  inhabitants = Math.floor((Math.random()*900)+100); 
    	  generateLandPlots();	
    	}
    	
    function generateLandPlots() 
    	{
    	var random_plot = Math.floor((Math.random()*30)+10); // find a random value between 10-40. minimum ratio 10:1 and normal ratio of 40:1
    	land_plot = Math.ceil(inhabitants/random_plot); 	
    	
    	for(i=0;i<land_plot;i++) 
    	  {
    		land_plots[i] = new Array([' ', ' ', ' ', ' ', ' ', ' ', ' ']);
    	  }
    	  
    	/* SET INHABITANTS ON LAND PLOTS */
    	for(i=0;i<land_plots.length;i++)
    	  {
    		land_plots[i][0][0] =  Math.floor((Math.random()*90)+10);
    	  
    		  if (10*(land_plots.length-i)+total+90>inhabitants-10*(land_plots.length-i)) 
    			 {
    			    land_plots[i][0][0] = 10; 
    			 } 
    		  if(i==land_plots.length-2) 
    		     {
    				land_plots[i][0][0] = Math.floor((inhabitants - total) / 2); // make the altered value the minimum possible value
    				  if (land_plots[i][0][0] <0) { land_plots[i][0][0] = -(land_plots[i][0][0]);} // reciprocate the negative value to a positive value
    			 }	
    		  else if(i==land_plots.length-1) 
    		     {
    				land_plots[i][0][0] = Math.floor(inhabitants - total); // make the altered value the minimum possible value
    				  if (land_plots[i][0][0] <0) { land_plots[i][0][0] = -(land_plots[i][0][0]);} // reciprocate the negative value to a positive value
    			 }				 
    	
    		 total = total + land_plots[i][0][0];
    		  
    	  }
    	}
    	
    </script>
    
    </head>
    
    <body>
    <form id="form1" name="form1" method="post" action="#">
    
        <input type="submit" name="button" id="button" value="Generate Environment" onclick="generateEnvironment();return false;"/>
    </form>
    
    </body>
    </html>
    This should run as is in your browser. I use Firefox and Firebug DOM tab for testing.

    The portion of the code highlighted in red is the fixed dimensions of the array, within the array, that I would like the script to emulate.

    The portions highlighted blue show I create a new Array as a Global JavaScript variable, and then again once a condition is met in the script (in this case, a random number is generated).


    The unnecessary part of the code is highlighted green. This script generates an array as such

    array[0][0][0]
    or
    var array = [[[' ', ' ', ' ', ' ', ' ', ' ']]];

    while I would rather the script produce a 2-dimensional array like this

    array[0][0]
    or
    var array = [[' ', ' ', ' ', ' ', ' ', ' ']];

    As jscheuer1 indicated here
    var array = [[' ', ' ', ' ', ' ', ' ', ' ']];
    I believe by declaring the second new array in blue I've created another layer to the original array. However, if I remove the Global Array then the FOR loop won't generate an array like the one in jscheuer1's example, either because it was not declared properly earlier or remains undefined.

    I'm sure it's a simple solution though.
    Last edited by sniperman; 12-30-2010 at 05:30 AM.

  6. #5
    Join Date
    Apr 2009
    Location
    Sydney, Australia
    Posts
    118
    Thanks
    16
    Thanked 1 Time in 1 Post

    Default

    Ok, thanks to jscheuer1's clear explanation (thanks!) i've been able to go through my code and figure out what was wrong and make corrections.

    I changed

    Code:
     var land_plots = new Array([' ', ' ', ' ', ' ', ' ', ' ', ' ']);
    to
    Code:
    var land_plots = [];
    and then again

    Code:
    	for(i=0;i<land_plot;i++) 
    	  {
    		land_plots[i] = new Array([' ', ' ', ' ', ' ', ' ', ' ', ' ']);
    	  }
    to
    Code:
    	for(i=0;i<land_plot;i++)
    	  {
    		land_plots[i] = [' ', ' ', ' ', ' ', ' ', ' ', ' '];
    	  }
    then changed all the references to those arrays from 3 deep to 2 deep...


    and VOILA

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
  •