Deep copy vector in AS3

In AS3, we can copy an array in two ways:

newArr = oldArr.concat();

or

var ba:ByteArray = new ByteArray();
ba.writeObject(oldArr);
ba.position = 0;
newArr = ba.readObject() as Array;

But these two methods do not work with Vector when I need to copy a vector with a complex data type. As is the case Vector.<Point>. When I use ByteArray to copy Vector with a complex data type, the compiler says that the new vector I copy the old to null.

+3
source share
2 answers

Register an alias of class c flash.net.registerClassAliasbefore writing your object to ByteArray, for example:

var points:Vector.<Point> = new Vector.<Point>();
var pointsCloned:Vector.<Point>;
var ba:ByteArray = new ByteArray();

registerClassAlias("flash.geom.Point", Point);

points.push(new Point(1, 2));
points.push(new Point(3, 4));
points.push(new Point(5, 6));

ba.writeObject(points);
ba.position = 0;
pointsCloned = ba.readObject() as Vector.<Point>;

trace(points);
trace(pointsCloned);

Thanks to this post!

+3
source

Another option is to use .map(), for example:

function pointCloner(item:Point, index:int, vector:Vector.<Point>):Point {
    return item.clone();
}

var newVector:Vector.<Point> = oldVector.map(pointCloner);
0
source

All Articles