views:

2625

answers:

4

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?

A: 

There is a function called forEach which both Vector and Array has which you can use. Basically it calls a function for each element in the vector. This is how it works:

var myVector:Vector.<Foo> = new Vector();
var myArray:Array = [];

myVector.forEach(arrayConverter);

function arrayConverter(element:*, index:int, array:Array):void{
    myArray[myArray.length] = element;
}

But I couldn't find a function which just moves all the values from the Vector to an Array. Another solution could be that you create a class which extends the Vector class and then you have a public function called toArray() and then you have that code in that function so you don't have to write it each time you want to convert.

Vector documentation

Ancide
very nice, but extremely slow ... you realize how many calls this makes?
back2dos
yes, in my opinion it's nicer than using a for/for each loop. It's a function call for each element in the Vector. How much slower exactly is this approach?
Ancide
+2  A: 

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

back2dos
A: 

a function call for each element in the Vector would be a LOT slower, particularly in a longer Vector. however, these examples are probably all equivalent, unless you're dealing with a fairly long Vector/Array -- legibility and ease of use are generally more important than optimization.

that said, i think the fastest way is to use a while loop with an iterator compared against 0.

var myArray:Array = new Array(myVector.length);
var i:int=myVector.length;
while (i--) {
    myArray[i] = myVector[i];
}

unfortunately, you can't stuff this technique into a method for ease of repeated use, because there's no way to specify a Vector method parameter of a generic base type.... :(

ericsoco
+1  A: 

If you have a vector of strings, you could do:

myArray = myVec.join(",").split(",");

for a quick and dirty Array conversion.

Good luck ~ Tyler

Tyler Wright