Clear or Delete an Array in AS3

Here is how to delete and clear out an array using the Slice method in Flash Actionscript 3

In this example we defined an array called people and fill it with three names. Than we use the Slice method by setting the first parameter index to 0 (zero represents the first element in the array) and the second parameter to full length of the array. people.length should equal 3. If you trace do a trace on the array people, it should return an “undefined”.

var people:Array = new Array();
people.push ("Bob");
people.push ("Alex");
people.push ("Frank");
// clear the array
people.splice(0,people.length);
trace(people[0]);

You could also store the deleted strings in to a second array for future reference. Here is how to assign those strings to a new deleted_people array:

var people:Array = new Array();
people.push ("Bob");
people.push ("Alex");
people.push ("Frank");
// clear the array
var deleted_people:Array = people.splice(0,people.length);
trace(deleted_people); // Bob, Alex, Frank

8 Responses

  1. SP

    splice(0) is faster that splice(0, array.length);

  2. ML

    setting the array to empty works too:

    (using the example)
    people = [];

  3. chema

    I wouldn’t use = [] to clear out an array since it won’t remove items in a referenced array.

    var original:Array = new Array();
    original.push( blah );
    original.push( blah );
    original.push( blah );

    var reference:Array = original;

    reference = []; // surprisingly, ‘reference’ had no items after this, but the original array remained untouched, so I had to use reference.splice(…)

  4. I’m surprised I’ve never ran across this! I always clear by

    var arr: Array = new Array();
    arr.push(i);
    arr = [];

    So one should not clear by = [] ?!?

    • Ken

      I believe the reason why:

      reference = [];

      does not clear the original array is because it’s the same as saying:

      reference = new Array();

      in which case the ‘reference’ variable simply refers to a new array object. The only time

      reference = [];

      would work for clearing an array is if it is the only reference to that array. In which case Flash’s garbage collector would clean it up (hopefully).

  5. bh

    Go through the array and pop() off all the items. With smallish arrays this appears to be faster than setting to [] or new Array().

  6. Saint74

    If your only clearing your array, would it better to just use the following?

    var hurray:Array = new Array;
    hurray.push (“dirtyMop”);
    hurray.length = 0;
    trace(hurray);

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Next Post » »