Indexing Anything
Indexing is a little bit special in ECMAScript languages like AS3, AS2, and JavaScript. MXMLC will gleefully let you index just about anything, even if there isn’t a chance it’ll work.
Consider the normal indexing one might do instead of using the dot operator:
var obj:Object = {name:"Jackson", profession="coder"}; obj["name"]; // equivalent to obj.name
This is handy because you can index with any string, not a known property. In this example, a loop is able to handle many properties on object, not just the ones the programmer knows ahead of time:
// Make an object with 100x100 gray shapes var grays:Object = {}; for (var i:int = 0; i < 256; ++i) { var cur:Shape = new Shape(); cur.graphics.beginFill(i | (i << 8) | (i << 16); // same in all channels cur.graphics.drawRect(0, 0, 100, 100); cur.graphics.endFill(); grays["gray " + i] = cur; }
This is a great feature that would require a specially-created data structure (like a map or a hash) in other languages (like C or Java). Then, of course, there’s these little bits of strangeness I discovered this week:
var n:Number = 3; n["hello"] = true;
3["hello"] = true;
Rather than giving a compiler error or warning, these throw an error at runtime:
ReferenceError: Error #1069
So, don’t think you can go adding on fields to basic types like Number or String like you can in other languages like Ruby. Instead, unfortunately, all I have to give you is another thing to watch out for. So watch out!
#1 by Robert Penner on September 16th, 2009 ·
The compiler will completely look the other way when you use bracket access to properties.