AS3: How to convert a Vector to an Array

Dan Homerick picture Dan Homerick · Jul 10, 2009 · Viewed 28.2k times · Source

What's the nicest way to convert a Vector to an Array in Actionscript3?

The normal casting syntax doesn't work:

var myVector:Vector.<Foo> = new Vector();
var myArray:Array = Array(myVector); // calls the top-level function Array()

due to the existance of the Array function. The above results in an array, but it's an array with a single element consisting of the original Vector.

Which leaves the slightly more verbose:

var myArray:Array = new Array();
for each (var elem:Foo in myVector) {
    myArray.push(elem);
}

which is fine, I guess, though a bit wordy. Is this the canonical way to do it, or is there a toArray() function hiding somewhere in the standard library?

Answer

back2dos picture back2dos · Jul 10, 2009

your approach is the fastest ... if you think it's to verbose, then build a utility function ... :)

edit:

To build a utility function, you will probably have to drop the type as follows:

function toArray(iterable:*):Array {
     var ret:Array = [];
     for each (var elem:Foo in iterable) ret.push(elem);
     return ret;
}