4

i am new of javascript, i have been told by someone, he said "speak strictly, javascript doesn't have multidimensional Array and associative array ". but in a book, i saw the following

var my_cars=Array();
my_cars["cool"]="Mustang";

$a=Array(Array(0,1),2);

so the opinion form he is wrong? am i right?

zhuanzhou
  • 2,409
  • 8
  • 33
  • 51

3 Answers3

5

JavaScript has arrays of whom their elements can be other arrays.

However, JavaScript has Objects with properties, not associative arrays.

Buy a better book.

  1. [] is much better than Array(). Also, why not instantiate an Array object explicitly then rely on Array returning a new object?
  2. The example is setting the property cool on the Array.
  3. Why the $a sigil? Why no new operator again?
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    Yes, JS:TGP is essential reading for anyone who does anything more than dabble with Javascript. Also, MDC's JS reference is a fantastic resource. See, e.g.: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#section_20 – entropo Apr 29 '11 at 01:34
4

All the explanations of Javascript Multidimensional arrays seem to be very convoluted, after almost an hour of research I came across this simple example:

var myArray = new Array();
myArray['row1'] = { 'col1':'BLARGH!!!', 'col2':'HONK!!!!' }
myArray['row2'] = { 'col1':'FOO!!!', 'col2':'BAR!!!!' }
myArray['row3'] = { 'col1':'FOUR!!!', 'col2':'GREGS!!!' }

document.write(myArray['row2']['col1'] + " - " + myArray['row3']['col2']);
//will output: FOO!!! - GREGS!!

I found it here: http://moblog.bradleyit.com/2009/06/create-multidimensional-associative.html

Paul Mason
  • 1,818
  • 2
  • 20
  • 32
  • Thanks for mentioning it, excellent! And I test it more and this is how to do it for a non associative: `var myArray = new Array(); myArray[0] = {0:1}; alert(myArray[0][0]);` – Melsi Oct 26 '11 at 17:56
2

The line: my_cars["cool"]="Mustang"; is actually not adding a value into the array. It is in fact adding a new property and value to the object my_cars. The following code would also work same:

var my_cars = new Function();
my_cars["cool"]="Mustang";
alert(my_cars["cool"]);

var c = new Object();
c["cool"]="Corvette";
alert(c["cool"]);

To understand how this works, you can check out my blog post on arrays and maps.

Btw, as @alex says, Buy A New Book.

Community
  • 1
  • 1
rahulmohan
  • 1,285
  • 11
  • 19