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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With