Javascript Associative Array Empty?

I was trying to form an associative array in javascript and made the mistake of trying to form it with the following code.

var data = new Array();
data['foo'] = 'test';

When I dumped the variable I found it was empty. As to be expected, this is another strange design feature of Javascript. Rather than storing the values in an arary, that syntax creates new properties on the object. However, the associative array behavior can still be replicated using the following syntax:

var data = {};
data['foo'] = 'test';

This sets data equal to a blank object instead of an Array object and now it will behave as normal.

This entry was posted in Html, JavaScript and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>