ActionScript 2: Cast object to array

Explicit conversion (casting) in ActionScript2 is very easy. Just put the variable in parentheses and precede the (new) type you want to cast to, like:

var i:Number = 1;
var b:Boolean = Boolean(i);
trace(b); // outputs "true"

Trying to cast an object to an array using this technique does not result in the expected output. As the following example shows, “Array(object)” always results in a new array with one entry:

var o:Object = [1,2];
var a:Array = Array(o);
trace(a.length); // outputs "1"
trace(a[0]); // outputs "1,2" 
trace(a[1]); // outputs "undefined"

The following code snippet does the trick:

var o:Object = [1,2];
var a:Array = {a:o}["a"];
trace(a.length); // outputs "2"
trace(a[0]); // outputs "1" 
trace(a[1]); // outputs "2"

The reason for Array(object) does not work as expected is that Array() is a predefined “global conversion function” that creates a new array and take the given argument(s) as entries. Adobe’s documentation says:

You can’t override primitive data types that have a corresponding global conversion function with a cast operator of the same name. This is because the global conversion functions have precedence over the cast operators. For example, you can’t cast to Array because the Array() conversion function takes precedence over the cast operator.