Initializing an Associative Array in Javascript

Ian presented the following question to me: How do you initialize an associative array with default values in javascript? There is plenty of posts out there on the internet in regards to creating arrays, most look something like:

var myArray = new Array();
myArray["something"] = "some value";

and so on. But what he was looking for was something more like the php method:

$myArray = ( "something"=> "some value", "something else" => "another value");

after a small amount of scouring remembering something about colons, I finally found a scathing post by someone with the revelation: Javascript doesn't actually have associative arrays. In fact javascript doesn't have arrays at all. It has objects. So how do you initialize an associative array in javascript? You don't. You initialize an object:

var arrayTest = {"something":"1st Result","second":"2nd Result"};

Hopefully that helps someone out there in Google land.


Jeff said...

Basically you are dealing with json (javascript object notation) very very useful.

Post a Comment