ActionScript: How to assign arrays using VALUE rather than REFERENCE?

I'm not familiar with working with an ActionScript array assignment by reference methodology. I understand what he is doing, but for some reason I am embarrassed to manage many arrays using this methodology. Is there an easy way to work with ActionScript arrays where array assignment is done using VALUE rather than REFERENCE? For example, if I want to assign oneArray to twoArray without binding two arrays to each other forever in the future, how can I do this? Will this work?

 var oneArray:Array = new Array("a", "b", "c"); var twoArray:Array(3); for (ii=0; ii<3; ii++) { twoArray[ii] = oneArray[ii]; } 

The goal is to be able to modify twoArray without seeing the change in oneArray .

Any advice on how to assign arrays of VALUE instead of REFERENCE?

---- for reference ----

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html

Array assignment is done by reference, not by value. When you assign one array variable to another array variable, both refer to the same array:

 var oneArray:Array = new Array("a", "b", "c"); var twoArray:Array = oneArray; // Both array variables refer to the same array. twoArray[0] = "z"; trace(oneArray); // Output: z,b,c. 
+7
source share
4 answers

You can clone an array to ensure there are two separate copies with the same values ​​in each Array element:

 var oneArray:Array = new Array("a", "b", "c"); var twoArray:Array = oneArray.concat(); twoArray[0] = "z"; trace(oneArray); // Output: a,b,c 

Hope this is what you are looking for.

+5
source

It looks like you are looking for the slice method. It returns a new array consisting of a set of elements from the original array.

 var oneArray:Array = new Array("a", "b", "c"); var twoArray:Array = oneArray.slice(); twoArray[0] = "z"; trace(oneArray); 

EDIT: note that the slice makes a shallow copy, not a deep copy. If you are looking for a deep copy, follow the link provided in the comment.

+10
source

If I understood the question correctly, you could do this:

 var collection= new ArrayCollection(["a", "b", "c"]); var clonedCollection = new ArrayCollection(ObjectUtil.copy(collection.source) as Array); // a, b, c trace(collection.toString()); // a, b, c trace(clonedCollection .toString()); clonedCollection.removeItemAt(0); // a, b, c trace(collection.toString()); // b, c trace(clonedCollection .toString()); 
0
source

You can create a clone function to copy an object using ByteArray.writeObject , and then exit to a new object using ByteArray.readObject , as described in liveocs.adobe.com - Cloning Arrays .

Note that writeObject and readObject will not understand objects more complex than Object and Array .

-2
source

All Articles