views:

798

answers:

4

I'm writing an application in Flex / ActionScript and have a number of class member variables of type Array storing data.

My question is: what's the "best" way to clear out an Array object?

I noticed the ArrayCollection class has a function removeAll() which does this, but the basic Array class does not. Some possibilities I've considered are:

  • Iterating through the array, calling pop or shift on each element
  • Setting the array length to 0
  • Setting the member variable to a "new Array()" or "[]"
+7  A: 

I'd say:

myArray = [ ];

That's explicit, short, and makes good use of the VM's garbage collector.

Your first alternative runs a lot of interpreted code to get the same result.

I don't know that the second does what you want; if it does, it's hacky, unclear.

The "new Array()" variant of the third alternative is just wordy, offering no advantage over an array literal. If you also write JS and use JSLint, you'll get yelled at for not using the array literal form.

Warren Young
Set length = 0 is not hacky as the official as3 lang ref mentioned it: http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Array.html#length. I personally use this method too. And I agree with Christopher W. Allen-Poole that your method is not clearing the array actually.
Andy Li
+4  A: 

It depends on your context. While using Mr. Young's answer is often the most correct way to do things, it will not always work, especially if you have two variables pointing to the same array:

var foo:Array
var bar:Array
foo = bar = [ 1, 2, 3 ];
bar = [];
trace( foo ); // 1,2,3

On the other hand, if you actually empty the array manually:

var foo:Array
var bar:Array
foo = bar = [ 1, 2, 3 ];
var l:int = bar.length; // get the length FIRST! 
                        // Otherwise bar.length will change
                        // while you iterate!

for( var i:int = 0; i < l; i++ )
{
    bar.shift();
}
trace( foo ); // does not trace anything
Christopher W. Allen-Poole
while(bar.length > 0) bar.shift(); // :)
Brian Hodge
bar.splice(0); // No loop needed :)
Sly_cardinal
+3  A: 

If you can modify the array reference, then I would go with Warren's answer. If you need to modify the existing instance, you can also use Array.splice:

var arr : Array = [1, 2, 3, 4, 5];

arr.splice(0, arr.length);
Richard Szalay
+1  A: 

I'm afraid to say but Warren Young is wrong when he said that setting the myArray = [] cause the garbage collector to pick up the array.

as you have the ability to add a reference to itself within itself, and therefore would never be collected and using up memory, especially if the array has some Sprites in the array, as they too would have the array references them and they too would never be collected.

Sly_cardinal and Richard Szalay are 100% correct. but the length parameter is not needed in Richard's.

To totally clear the array and make sure its collected by garbage then

myArray.splice(0);
myArray = null;
WORMSS