Cloning Arrays in Flash AS3
Thursday, July 29th, 2010So I thought I might share something I learned today about Arrays in Flash AS3. In most languages I’ve used, it’s fairly simple to clone an array. For instance:
In Javascript:
- var x = new Array(‘Bob’,'Tom’,'Joe’);
- var y = x;
- y[1] = “Stan”;
- // x contains Bob, Tom, Joe
- // y contains Bob, Stan, Joe
In PHP:
- $x = array(‘Bob’,'Tom’,'Joe’);
- $y = $x;
- $y[1] = “Stan”;
- // $x contains Bob, Tom, Joe
- // $y contains Bob, Stan, Joe
However in Flash you would get:
- var x:Array = new Array(‘Bob’,'Tom’,'Joe’);
- var y:Array = x;
- y[1] = “Stan”;
- // x contains Bob, Stan, Joe
- // y contains Bob, Stan, Joe
What? Why? Because Flash automatically creates a reference when you assign arrays to each other, it does not clone the arrays like the other languages. You can do something like that in PHP with the &= assignment operator, but it’s not the default. Why would Flash not do the same as PHP? How does it make any sense that when I assign one thing a value that the two values should then be tied together automatically?
There is a solution. The Flash help system actually talks about this problem here. So the new code would look like:
- var x:Array = new Array(‘Bob’,'Tom’,'Joe’);
- var y:Array = x.concat();
- y[1] = “Stan”;
- // x contains Bob, Tom, Joe
- // y contains Bob, Stan, Joe
Basically, whenever you use the concat method it automatically returns a new array (rather than a reference), which solves the problem. But, if you have a multidimensional array, this method does not work. Concat does not touch the arrays within the arrays – it only converts the initial values in the base array. Fortunately Flash’s help system recommends the following code (which works):
- import flash.utils.ByteArray;
- function clone(source:Object):*
- {
- var myBA:ByteArray = new ByteArray();
- myBA.writeObject(source);
- myBA.position = 0;
- return(myBA.readObject());
- }
- var x:Array = new Array(‘Bob’,'Tom’,'Joe’);
- var y:Array = clone(x);
- y[1] = “Stan”;
- // x contains Bob, Tom, Joe
- // y contains Bob, Stan, Joe
So I’m glad to have a solution, but it seems awfully weird to have to go to so much trouble…


