Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3:removing every elements in an array at once using for loop

EDIT: EVERY ANSWER BELOW ARE WORKING, THANKS FOR HELPING ME!

I'm currently learn about splicing an array in as3. So here's my code:

//import classes
import flash.utils.Timer;
import flash.events.*;

//variables
var Arr:Array=new Array();
var num:Number=0;
//set a timer and set timer limit of 10 times
var timer:Timer=new Timer(1000,10);

//add a listener to our timer object
timer.addEventListener(TimerEvent.TIMER, tick);
timer.addEventListener(TimerEvent.TIMER_COMPLETE,tock);

//tick function
function tick(e:TimerEvent):void{
    //i add an element each time the timer 'ticks'
    Arr.push(['index'+num]);
    num++;
}
//tock function
function tock(e:TimerEvent):void{
trace('array elements :'+Arr);//traces Arr elemnts
for(var i:int=0;i<Arr.length;i++){
    Arr.splice(i,1);// i've tried Arr.splice(0,1), but neither working
    trace('elemnts left : '+Arr);
}

I dont really understand the problem, but here's the result:

1.not every elements in Arr array have been removed 2.the maximum Arr's length is ten before spliced.BUT in the loop, its only splicing less than ten times, which it causes the problem above

anybody have an idea for this? Please help me out

like image 571
Yudhis Avatar asked Jan 28 '23 17:01

Yudhis


1 Answers

There are simpler and faster options:

You can just set the Array's length to 0. That will effectively remove all its elements at once.

Arr.length = 0;

You can create a new empty instance of the Array class. That will not destroy the original object immediately, but if there are no references to it, it will be consumed by the Garbage Collector eventually, so you won't need to think of it.

// You can omit () with the "new" operator if there are no mandatory arguments.
Arr = new Array;
like image 136
Organis Avatar answered Feb 16 '23 03:02

Organis