Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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?

share|improve this question
up vote 5 down vote accepted

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?
share|improve this answer
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.: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… – entropo Apr 29 '11 at 1:34

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.

share|improve this answer

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

share|improve this answer
    
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

See: JavaScript Multidimensional Arrays

Please use search before asking new questions.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.