« Valentines Day a la Bitch | Main | Hello Kansas! Preso via Breeze »

Associative Arrays?

Found this in a file I've been helping with and it struck me as odd, I've never seen this syntax, didn't know you even do this and figured because all the code was dumped into the fla first frame, it was forgiven by the compiler:

data_array=[];
data_array.name="Stacey";
data_array.id="666";

trace(data_array.name);
trace(typeof(data_array));
trace(data_array instanceof Array);
trace(data_array instanceof Object);

-------------------------
I thought it was a serious ASWTF. And i still can't see why you would want to use an associative array. And at first, I was confused about why both the instanceof Array and Object brough back true, but 2 seconds later it dawned on me - inheritance.

What would be the benefits of using an associative array like this as opposed to a simple object? Are there any?

Things you learn while digging through code.

Posted by bitch at February 23, 2006 02:49 PM

Comments

You might use an Array this way if you wanted the Array functionality and add some properties to the actual array to identify it. But the potential to run into trouble is there since you don't want to overwrite existing methods and props.

typeof(my_array) will return object so you can't use that to identify an Array.

(my_array instanceof Array) will tell you if it's an Array, and is really the only way to differentiate an Array and an Object. (my_obj instanceof Array) will return false.

I started to write my own Array class based on this. Then I realized how pointless it was and never finished. But it was an interesting exercise. :)

Posted by: Derek Vadneau at February 23, 2006 04:21 PM

Nothing strange here. The Array class extends Object and is dynamic so it basically behaves like any basic object. I would say that objects actually are very much like associative arrays.

What about this one:

var s = new String(" is a string");
s.name = "Joe";
trace(s.name+s);

Posted by: Philippe at February 23, 2006 04:39 PM

I was more just taken back by the array syntax - i mean if you are doing that, why not just use a plain ole object?

Posted by: Stacey at February 23, 2006 05:00 PM

Haha True dat Philippe! Had a contractor whip up some associative arrays filled with various objects with un-typed properties and it was a NIGHTMARE to debug at 2 am. There were so many better ways to do it.

Death to AS1! All praise 666, the id of the Bitch!

Cheers,
Brent

Posted by: Brent Bonet at February 23, 2006 07:05 PM

I like:

var myAr = new Array({title:"Hello",data:"world"});

Posted by: Mike Britton at March 1, 2006 06:10 PM




Remember Me?