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.

Comments

  1. Dave

    You could simply do:

    var o:Object = [1,2];
    var a:Array = o as Array;

  2. Jan Jonas

    Hi Dave,
    I think the as keyword was introduced in ActionScript 3. This blog post is about casting an object to array in ActionScript 2.

  3. Ho

    Thanks to your post, it is a good suggestion to use the as2.0 trick.

    Before I have a look to your post, I am stupid to using for…in function to loop over the object(API said multidimensional array) and then using all the elements in the object to create a new Array…= =

    Your trick is create a new Array which is a reference to obj
    And I wanna to have a new Array completely and finally I have find out a easy understand and short code through your post:

    //wrong test1
    var obj:Object = [1,2];
    var a:Array = Array(obj);
    trace(a.length); // outputs “1”

    //wrong test2
    var obj:Object = [1,2];
    var a:Array = obj; Flash warning error type!!

    //Your Trick
    var ob:Object = [1,2,3]
    var arr:Array = {haha:ob}[“haha”]
    arr.splice(0,1)

    trace(ob.length) //2
    trace(arr.length) //2
    trace(ob[0]) //2
    trace(arr[0]) //2

    //My Trick
    var ob:Object = [1,2,3]
    var arr:Array = ob.slice();
    arr.splice(0,1)

    trace(ob.length) //3
    trace(arr.length) //2
    trace(ob[0]) //1
    trace(arr[0]) //2

Leave a comment

Your email address will not be published. Required fields are marked *

*