Question

var ary:Array = ["string","string","string"];
var copy_ary:Array = ary;
trace(copy_ary);//string,string,string
ary[1]=false;
trace(copy_ary);//string,false,string

All I want to do is make a copy of the array ary without the copy constantly changing in accordance with the original. Would I have to create a copy with a loop (e.g. below)?

var ary:Array = ["string","string","string"];
var copy_ary:Array = [];
for(var i=0;i<ary.length;i++){
    copy_ary[i]=ary[i];
}

Obviously this works, but it seems a lot of work considering one wouldn't think the copied array would constantly stay the same as the original in the first place. Could someone please tell me why this is?

Was it helpful?

Solution

In your first example you didn't create a new array - you created a new reference to an already existing array (so you had 2 references but 1 array). When you modify the array through one reference, you'll see changes through the other reference as well (since you really only have 1 array).

To create an independent copy of an array, you need to actually create a new array instance and then copy the items over. This can be done through a shallow or through a deep copy.

In short, a shallow copy can be created using the Array.concat() or the Array.slice() methods (or using a loop, like in your 2nd example). For a deep copy, you'll have to also copy the objects inside the array - this would likely need more code, depending on what kind of objects are in the array.

When your array only contains primitive (or pimitive-like) types, a shallow copy is typically enough - if your array only has strings, a shallow copy should be enough since String behaves like a primitve type even though it's a complex object.

Read this article for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top