Monday, 5 December 2011

Array


The Array.concat Method and Cloning an Array

The method:
Array.concat(...args):Array
Concatenates the elements specified in the parameters with the elements in an array and creates a new array. If the parameters specify an array, the elements of that array are concatenated. For example:
var arr1:Array = [1,2,3];
var arr2:Array = ["green","blue"];
var arrResult:Array = arr1.concat(arr2);
trace(arrResult);
trace(arr1);
The outpput window shows:
1,2,3,green,blue
1,2,3
The array arr1 has not been altered. A new concatanated array arrResult=[1,2,3, "green","blue"]was created.
In particular, if you don't pass any parameters to the 'concat' method, you are creating a copy of your array:
var arrResult2:Array = arr1.concat();
trace(arrResult2);
gives the array 1,2,3. The copy of your array obtained via the 'concat' method is a shallow clone. That is, if elements of your array are objects other than primitive datatypes like numbers or strings, the objects are passed to the clone by reference only. So if the objects change, they will change in both the original array and in its clone.

No comments:

Post a Comment