Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript multidimensional Array and associative array

Tags:

javascript

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?

like image 219
zhuanzhou Avatar asked Dec 21 '22 14:12

zhuanzhou


2 Answers

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?
like image 84
alex Avatar answered Dec 28 '22 22:12

alex


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

like image 43
Paul Mason Avatar answered Dec 29 '22 00:12

Paul Mason