Reputation: 4246
I find it unfamiliar to work with ActionScript's array assignment by reference methodology. I understand what it's doing, but I somehow find it confusing to manage many arrays with this methodology. Is there a simple way to work with ActionScript arrays where the array assignment is by VALUE rather than REFERENCE? For example, if I want to assign oneArray
to twoArray
without linking the two arrays to each other forever in the future, how to do it? Would 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 intent is to be able to change twoArray
without seeing a change in oneArray
.
Any advice how to assign arrays by VALUE instead of REFERENCE?
---- for reference ----
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html
Array assignment is by reference rather than 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.
Upvotes: 8
Views: 1803
Reputation: 1
You can create a clone function to copy the object using the ByteArray.writeObject
and then out to a new object using ByteArray.readObject
, as described in livedocs.adobe.com - Cloning arrays.
Note that writeObject
and readObject
will not understand objects more complex than Object
and Array
.
Upvotes: -2
Reputation: 1481
You can clone the array to guarantee two seperate 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're looking for.
Upvotes: 6
Reputation: 713
If I understand 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());
Upvotes: 0
Reputation: 46027
Looks like you are looking for slice method. It returns a new array that consists of a range 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 slice does a shallow copy, not a deep copy. If you are looking for a deep copy then please follow the link specified in the comment.
Upvotes: 11