Unfortunately in Actionscript, it seems like support for the Vector class isn't fully there yet. There are some scenarios where I need to convert a Vector into an array (creating an ArrayCollection for example). I thought this would do the trick:
var myVector:Vector.<MyType> = new Vector.<MyType>();
var newArray:Array = new Array(myVector);
Apparently this just creates an array where the first index of the array contains the full Vector object. Is this my only option:
var newArray:Array = new Array(myVector);
for each(var item:MyType in myVector)
{
    newArray.push(item); 
}
I feel like that clutters up the code a lot and I need to do this in a lot of places. The Vector class doesn't implement any kind of interface, so as far as I can tell I can't create a generic function to convert to an array. Is there any way to do this without adding this mess every time I want to convert a Vector to an array?
There's no easy/fast way to do it, the best solution is to use an utility class like this one:
package {
    public class VectorUtil {
        public static function toArray(obj:Object):Array {
            if (!obj) {
                return [];
            } else if (obj is Array) {
                return obj as Array;
            } else if (obj is Vector.<*>) {
                var array:Array = new Array(obj.length);
                for (var i:int = 0; i < obj.length; i++) {
                    array[i] = obj[i];
                }
                return array;
            } else {
                return [obj];
            }
        } 
    } 
}
Then you just have to update your code to something like this:
var myArray:Array = VectorUtil.toArray(myVector);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With