How to copy an array as a new array?


(Bora Kasap) #1
private var A:Array = new Array();  
private var B:Array = new Array();
  

      
override public function added():void
{
this.A = GLOBALS.C;   //C is an array of numbers
this.B = this.A;
}
        
override public function update():void
{
this.B[0] -= 1;
}

this update function also effecting on array A and maybe effecting on C too, I couldn’t solve this, so i’ve used this for now;

this.B.length = 0;
for each(var x:Number in this.A)
{
this.B.push(x);
}

(Zachary Lewis) #2

From Adobe:

##Cloning arrays

The Array class has no built-in method for making copies of arrays. You can create a shallow copy of an array by calling either the concat() or slice() methods with no arguments. In a shallow copy, if the original array has elements that are objects, only the references to the objects are copied rather than the objects themselves. The copy points to the same objects as the original does. Any changes made to the objects are reflected in both arrays.

In a deep copy , any objects found in the original array are also copied so that the new array does not point to the same objects as does the original array. Deep copying requires more than one line of code, which usually calls for the creation of a function. Such a function could be created as a global utility function or as a method of an Array subclass.

The following example defines a function named clone() that does deep copying. The algorithm is borrowed from a common Java programming technique. The function creates a deep copy by serializing the array into an instance of the ByteArray class, and then reading the array back into a new array. This function accepts an object so that it can be used with both indexed arrays and associative arrays, as shown in the following code:

import flash.utils.ByteArray; 
 
function clone(source:Object):* 
{ 
    var myBA:ByteArray = new ByteArray(); 
    myBA.writeObject(source); 
    myBA.position = 0; 
    return(myBA.readObject()); 
}

(Jacob Albano) #3

This is faster:

var newArray:Array = oldArray.concat();

Note that in either solution the contents are copied by reference where possible, so modifying an entry in array A will also modify it in array B. If your array only contains numbers, each array will contain a copy and you can modify them separately.


(Zachary Lewis) #4

That’s the first thing Adobe said!

The second example is for making deep copies. Like, if someone wanted to duplicate an array of ten Entity objects but didn’t want them to be simple references.


(Bora Kasap) #5

Thanks again again again i’m gonna give a little thanks credit to you both and someone more, you helped me much for this game, i got the cloning, thanks


(Jacob Albano) #6

Whoops. :stuck_out_tongue: That’s what I get for reading too quickly.