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?

3 Answers 3

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?
Sign up to request clarification or add additional context in comments.

1 Comment

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/…
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

1 Comment

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]);
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.