Link to home
Start Free TrialLog in
Avatar of phooey
phooey

asked on

Multi-dimensional Arrays

How can I create a multi-dimensional array in JavaScript.

I currently have an array:

var ar = new Array ("A","B","C");

and I want to do:

var ar = new Array ("A":"1" , "B":"2" , "C":"3")

but this is not the correct sytax.

I know I can do
var ar = new Array[3][2];
and then assign the variables, but I want to do this when constructing the array.
Avatar of garrethg
garrethg

Michel is going to come along and beat me up for abusing arrays in a minute :), but I use:

var ar= new Array("A","B","C");
ar["A"]= new Array("1");
ar["B"]= new Array("2");
ar["C"]= new Array("3");

to query multidimensional arrays via a string.


ar[0] returns "A"

ar["A"] returns "1", or rather the value of the array containing "1" whose only value is "1"

ar["A"][0] returns "1"

ar[0][0] returns "A" because whimsical JS take the result of ar[0] and performs a index return on the string on NSN and undefined on MSIE 5.0

myVar= "A";
ar[myVar] returns "1"
ar[myVar][0] returns "1"

ar[ar[0]][0] returns "1"
ASKER CERTIFIED SOLUTION
Avatar of maneshr
maneshr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of phooey

ASKER

Is this the only way to do it?

Create an array of arrays?

I aws looking for some way that I can simply type the array in during the constructor and then query it via:

var temp = ar[0][0];
//displays "A"
var temp2 = ar[0][1];
//displays "1"
var temp3 = ar[2][1];
//displays "3"

but I guess you are saying that this is not possible?
Avatar of phooey

ASKER

Adjusted points to 100
Avatar of phooey

ASKER

Had a go...and it works...kind of !
I've added some points if you can let me know what's wrong with tihs code !
-------------------------------------

<HTML>
<HEAD>
<script>
<!--
function a(){
  for (i=1 ; i < arRecord.length; i++){
        for (j=1 ; j < arRecord[i] ; j++){
      alert (arRecord[i][j])
            }
      }
}
//-->
</script>


<TITLE>test</TITLE>
</HEAD>
<BODY>
<script type="text/javascript">
<!--
  arRecord = new Array()

  arRecord[1] = new Array()
  arRecord[1][1] = "A"
      arRecord[1][2] = "1"

  arRecord[2] = new Array()
  arRecord[2][1] = "B"
  arRecord[2][2] = "2"

  arRecord[3] = new Array()
  arRecord[3][1] = "C"
  arRecord[3][2] = "3"

// -->
</script>


<a href="" onClick="a(); return false;">click here</a>
</BODY>
</HTML>
Avatar of phooey

ASKER

Ignore that last bit !
Forgot a ".lenght".
Avatar of phooey

ASKER

Sorry, garrethg, but this answer was just easier to follow, altough after reading it, yours makes sense.
Nah, no problem it's an open forum. However just remember you can only query arRecord by index, if you want to query by string you need to use my example above.