When you remove elements from an array in a for statement, you need to change the value of the index variable accordingly : splice « Array « Flash / Flex / ActionScript






When you remove elements from an array in a for statement, you need to change the value of the index variable accordingly

 

package{
  import flash.display.Sprite;
  
  public class Main extends Sprite{
    public function Main(){
        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
    }
  }
}
// 4,10,,,1
// 4,10,,1

        








Related examples in the same category

1.Use slice( ) instead of concat( ) to create a copy of an array
2.The splice( ) method can add elements to, or remove elements from, an array.
3.Inserting Elements into an Array: arrayName.splice(startingIndex, numberOfElementsToDelete, element1[,...elementN]);
4.Removing Elements from Within an Array
5.Extracting Subsets of Array Elements
6.splice( ) can both remove elements from and add elements to an array.
7.splice( ) returns a new array containing the deleted elements