ProblemYou want to remove one or more elements from an array and shift any remaining elements to fill the vacant indexes. SolutionUse the splice( ) method to remove elements from the middle of the array. Use pop( ) to remove the last element or shift( ) to remove the first element. DiscussionRemove elements from an array by starting at a specified index using the splice( ) method. When using splice( ) to delete elements, you should pass it two parameters:
The splice( ) method also returns a new array containing the deleted elements; for example: var letters:Array = ["a", "b", "c", "d"]; // Remove two elements from letters starting at index 0. var deleted:Array = letters.splice(0, 2); // Display the deleted elements: "a" and "b". for (var i:int = 0; i < deleted.length; i++) { trace(deleted[i]); } To delete a single element from the beginning or end of the array, you can use the shift( ) and pop( ) methods. The shift( ) method removes the first element of the array and returns its value. The pop( ) method removes the last element of the array and returns its value: var letters:Array = ["a", "b", "c", "d"]; // Remove the first element and display its value. trace(letters.shift( )); // Remove the last element and display its value. trace(letters.pop( )); // Display the remaining elements. // The array has two elements left: "b" and "c". for (var i = 0; i < letters.length; i++) { trace(letters[i]); } When you remove elements from an array in a for statement, you need to change the value of the index variable accordingly. The following example illustrates what can happen if you don't update the value of the index variable: var numbers:Array = new Array(4, 10); numbers[4] = 1; trace(numbers); // Displays: 4,10,undefined,undefined,1 for(var i:int = 0; i < numbers.length; i++) { if(numbers[i] == undefined) { numbers.splice(i, 1); } } trace(numbers); // Displays: 4,10,undefined,1 In the preceding code, you might have expected it to remove both of the undefined elements from the array. However, as shown in the final trace, it removed only one. If you go through the for statement step-by-step, you can see why:
|