Converting Vectors to Arrays
Vectors– typed arrays in AS3– are much quicker than arrays and therefore very useful. There are many times where you end up with arrays though and need to convert them into vectors for the bulk of your using that data. This article is about that process.
The naive syntax does not work at all:
new Vector.<int>([2,4,6]);
You get a vector back that is totally empty. No compiler error. No compiler warning. Bummer. Instead, you should use the global conversion function:
Vector.<int>([2,4,6]);
Then you get the results you’re looking for: a vector of the three elements in the array you passed in. Now for a twist. What happens if the array you pass in contains elements that are not of the vector’s type? Let’s try:
var v:Vector.<int> = Vector.<int>(["2","4","6"]); trace(v); // 2,4,6 trace(v[2]+4); // 10
This is classic “Flash magic”. Behind the scenes, the player converts every element of the array just as you would expect with a regular cast. Now if only there was an easy way to convert a vector to an array. This leads to the second bummer of the post:
try { var v:Vector.<int> = Vector.<int>([2,4,6]); var a:Array = Array(v); var a2:Array = v as Array; trace("v: [" + v + "] len: " + v.length); trace("a: [" + a + "] len: " + a.length); trace("a2: [" + a2 + "] len: " + a2.length); } catch (err:Error) { trace("err: " + err); }
These are two seemingly-legitimate attempts to convert the vector to an array. Why can’t you just use the global Array cast like the Vector was created? You get this compiler warning:
Warning: Array(x) behaves the same as new Array(x). To cast a value to type Array use the expression x as Array instead of Array(x). var a:Array = Array(v);
Which yields you an array of one element: the vector. So you take its advice and try the latter. You get a runtime error:
err: TypeError: Error #1009
So I don’t know of a way to do the vector-to-array cast without brute-forcing it. If anyone knows, please tell me. Here’s the brute force way, just in case you’re wondering:
function vectorToArray(v:Object): Array { var len:int = v.length; var ret:Array = new Array(len); for (var i:int = 0; i < len; ++i) { ret[i] = v[i]; } return ret; }
Unfortunately, the parameter can’t be typed since that would require specifying the type of elements the vector contains. This is a big drawback! It destroys type safety and makes all accesses of the vector dynamic. If only AS3 had a proper templating system…
#1 by Daniel Wabyick on December 18th, 2009 ·
I just hit this same issue. Really annoying, and makes it quite frustrating to use in Flex !
#2 by Claudius Tiberiu Iacob on November 19th, 2012 ·
Found on “http://stackoverflow.com/questions/1107809/as3-how-to-convert-a-vector-to-an-array”:
var toArray : Array = [].concat(toVector);
#3 by ChessMax on June 29th, 2014 ·
This code actually constructs a one-element array with the vector as the first value.