[thelist] Q on assoc arrays
Simon Willison
cs1spw at bath.ac.uk
Sun Dec 14 20:41:03 CST 2003
jsWalter wrote:
> In Perl I can do this...
>
> ( 'ac' -> 'Ascension Island',
> 'ad' -> 'Andorra',
> 'ae' -> 'United Arab Emirates',
> 'af' -> 'Afghanistan'
> )
>
> Does any one know if JavaScript has a similar "feature"?
> I would rather not have to do...
>
> myArray['ac'] = 'Ascension Island';
> myArray['ad'] = 'Andorra';
> myArray['ae'] = 'United Arab Emirates';
> myArray['af'] = 'Afghanistan';
Javascript is actually implemented almost entirely on top of hash
tables. Objects are hashes, variable scope is handled by hashes, global
variables are in a hash - if you ever look under the hood of a
Javascript interpreter most of what it does involves some kind of hash.
The critical point for your purpose is that objects are hashes. A
Javascript object is simply a data structure that groups a load of names
with their associated values - it just so happens that these values can
be code as well as normal data.
The solution to your problem is to use "object literal" syntax, which
looks like this:
var myArray = {
ac: 'Ascension Island',
ad: 'Andorra',
ae: 'United Arab Emirates',
af: 'Afghanistan'
};
That will create an object called "myArray" prepopulated with all of
your data.
Here's an interesting side-note: if you do the above, you'll be able to
access data from the object using either of the following forms:
var country = myArray['ac'];
or
var country = myArray.ac;
As far as the Javascript interpreter is concerned, they mean the same
thing. The advantage of the [''] syntax is that it takes a string, which
you can construct dynamically or obtain from elsewhere in your program.
You could potentially do the same thing with eval('myArray.'+key) but
eval is a dirty, dirty hack (and comes with an extra performance hit as
well).
Hope that helps,
Simon Willison
More information about the thelist
mailing list