Log in

View Full Version : What's proper syntax to create multi arrays



sniperman
12-28-2010, 01:34 PM
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


var array = new Array([' ', ' ', ' ', ' ', ' ', ' ']);

which shows up as

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


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

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?

vwphillips
12-28-2010, 04:25 PM
<!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


<!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>

jscheuer1
12-29-2010, 03:51 PM
@sniperman

Part One:

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



var array = [[],['b','c'],[],[],[],[]];

That's the proper way to create a multidimensional array.

One could also do it like so:


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:


['b','c']

and transforms it into:


[0,1,2,3]

so the base array (array) now equals:


[[],[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:



var array = new Array([' ', ' ', ' ', ' ', ' ', ' ']);

That should be:


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:



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:


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?

sniperman
12-30-2010, 05:09 AM
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.


<!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.

sniperman
12-30-2010, 05:38 AM
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


var land_plots = new Array([' ', ' ', ' ', ' ', ' ', ' ', ' ']);
to

var land_plots = [];
and then again


for(i=0;i<land_plot;i++)
{
land_plots[i] = new Array([' ', ' ', ' ', ' ', ' ', ' ', ' ']);
}
to

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