How to create a shallow copy of an array in ActionScript 3

var a:Array = ["a","b","c"]; var b:Array; /* insert code here to copy 'a' and assign it to 'b'*/ 
+4
source share
3 answers

Adapted from the As3 manual:

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

Concat is the way to go if you choose concat and slice, since concat is faster in terms of performance.

Read more about this here: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ee7.html

To clarify:

  private function shallowCopy():void{ var a:Array = ["h", "e", "l", "l", "o"]; var b:Array = a.concat(); trace("Shallow copy:"); trace("Before delete: " + a); trace("Before delete: " + b); delete a[0]; trace("After delete: " + a); trace("After delete: " + b); } 
+11
source

Corresponding line:

 var b:Array = a.concat(); 
+7
source

If the array contains only string or numeric values, it is enough to make a β€œshallow” copy, as described by Adam and Retterberg.

If the array contains other arrays or objects / instances of classes, etc., then you should make a deep copy if you need all the objects inside to be unique, not just links. You can achieve this with:

 var ba:ByteArray = new ByteArray(); ba.writeObject(a); // Copy the original array (a) into a ByteArray instance ba.position = 0; // Put the cursor at the beginning of the ByteArray to read it var b:Array = ba.readObject(); // Store a copy of the array in the destination array (b) ba.clear(); // Free memory 

It is also useful for copying objects that do not have any concat or splice methods.

0
source

All Articles