Friday, 21 May 2010

How to erase a element in a Array

I came across this problem recently.


The Array has some methods, and the most common are PUSH, that lets you put an element in a Array. This element will go to the end.


And then you have the POP method, but this only gets the last element in a Array.


Now the question is "How do I delete an element giving the position for that element"?


It's a bit trickier, and it's done using another method called SPLICE.


The syntax is:
splice(startIndex:int, deleteCount:uint... values)


This means:
- startIndex -> Initial position were you want to delete. It's the index position of the Array;
- deleteCount ->This is how many elements you want to delete, that includes the index position you specified in startIndex. If you say 1, then it will delete the index position that you've specified. If you say 2, then it's the index position, and the next element... and so on.


As an example:


var myList:Array=new Array("Blue", "Red", "Green", "Black,"White");


myList.splice(2,2);
trace(myList); //Blue, Red, White


//Green is Index number 2, and then deletes two elements including Green, which are Green and Black