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?
JavaScript has arrays of whom their elements can be other arrays.
However, JavaScript has Object
s with properties, not associative arrays.
[]
is much better than Array()
. Also, why not instantiate an Array
object explicitly then rely on Array
returning a new object?cool
on the Array
.$a
sigil? Why no new
operator again?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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.