May 20

Associate array are bad in JavaScript

Date: May 20, 2009. Comments»

Associate array in javascript: An array is a linear allocation of memory in which elements are accessed by integers that are used to compute offsets. Arrays can be very fast data structures. Unfortunately, JavaScript does not have anything like this kind of array. Instead, JavaScript provides an object that has some array-like characteristics. It converts array subscripts into strings that are used to make properties.

>>foo = new Array()
>>foo[100] = 'bar'
>>foo.length
101

You can call foo as anything you like (Boolean, or Date, or String) all will work. It works because all you are doing is setting properties on an object in JavaScript foo['bar'] and foo.bar is one and same. When you iterate on the foo all you do is iterating on the properties. Remember all data type in JavaScript are object. Use array as a object and don't store key/value pairs.

>> foo['bar'] = 'buz'
>> foo['foobar'] = 'foobarbuz'
>> foo.length
0

Comments

Sam - June 14, 2009.
Hi, Coming from the php background I use to do associate array in javascript, thanks for en-lighting me.
Leave Comment: