Actionscript – Best way to remove all elements from an ActionScript Array

actionscriptactionscript-3apache-flex

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 "[]"

Best Answer

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.