O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Separate Copy of an Array

Problem

You want to make an exact copy (a duplicate) of an array—one that contains all of the elements found in the original, but is not just another reference to the original.

Solution

Use the concat() method or the slice() method. Optionally, you can use the ArrayUtilities.duplicate() method. The duplicate() method can create recursive duplicates.

Discussion

Because arrays are a composite datatype, they are copied and compared differently from primitive data. A variable that holds an array doesn’t truly contain all of the array’s data. Instead, the variable simply points to the place in the computer’s memory where the array’s data resides. This makes sense from an optimization standpoint. Primitive data tends to be small, such as a single number or a short string. But composite data, such as an array, can be very large. It would be inefficient to copy an entire array every time you wanted to perform an operation on it or pass it to a function. Therefore, when you try to copy an array, ActionScript doesn’t make a separate copy of the array’s data. A simple example illustrates this.

First, let’s look at how primitive data is copied from the variable quantity to another variable, newQuantity:

// Assign the number 5 to a variable.
var quantity:int = 5;

// Copy quantity's value to another variable, newQuantity. 
var newQuantity:int = quantity;

// Change quantity's value. quantity = 29; trace(quantity); // Displays: 29 trace(newQuantity); // Displays: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required