Friday, May 20, 2011

Associative JavaScript Arrays by Numeric 'ID'

I needed to keep browser-side information about certain objects by numeric ID.
When using an associative JavaScript array like this:

var gadgets;
gadgets[4711].name = 'Fred';
gadgets[4711].color = 'red';

you will find that it creates an array with (mostly empty) elements gadgets[0] to gadgets[4711].
On the other hand, when initializing the array like this:

gadgets['4711'].name = 'Fred';

it creates a single element in an associative container. Once created, you can access such elements with either gadgets[4711] or gatgets['4711']!