Advertisement |
Removing an item from an Array
You might for some reason want to remove an item from an array. Just like the process for addition, there are a number of methods for removing items from an array. The main tool for removing items from an array is the splice() method. This method can be used to remove one or more items from an array by specifying the starting index and then the number of items that should be removed from that starting point. It is used in the following format:
myArray.splice(StartingIndex, deleteCount)
So, for example, if we wanted to remove the element at index 2 of the array we can use the following code:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray.splice(2,1);trace(myArray);
myArray.splice(2,1);trace(myArray);
Testing this code should output the following: "Flash,ActionScript".
If we do not provide a delete count the splice() method will delete everything that comes after the starting index. In the example below, if we wanted to delete everything after the first item in the array we would do it this way:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray.splice(1);trace(myArray);
myArray.splice(1);trace(myArray);
Testing this code should output the following: "Flash".
Alternatively, you can use the pop() method to remove the last item within an array without having to worry about the actual index number:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray.pop();trace(myArray);
myArray.pop();trace(myArray);
Testing this code should output the following: "Flash,ActionScript".
The pop() method has a more limited functionality because it can only remove the last element from an array, unlike splice() which can remove any element regardless of its position, but then again it could be helpful in certain projects that require this functionality.
0 comments: