O'Reilly logo

Actionscript Cookbook by Joey Lott

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

6.8. Creating a Separate Copy of an Array

Problem

You want to copy an array, but y ou want the duplicate to be dissociated from the original array.

Solution

Use the concat( ) method or the slice( ) method.

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 very 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 necessarily 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 myNumber to another variable, myOtherNumber:

// Assign the number 5 to a variable.
var myNumber = 5;
// Copy myNumber's value to another variable, myOtherNumber. 
var myOtherNumber = myNumber;
// Change myNumber's value.
myNumber = 29;

trace(myNumber);        // Displays: 29
trace(myOtherNumber);   // Displays: 5

When the copy is made, the contents of myNumber are copied to myOtherNumber. After the copy is made, subsequent changes to myNumber have no effect on myOtherNumber ...

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