introduction to web programming Deleting and replacing list elements with the splice function The splice function is used to remove or replace elements in an array and uses the following syntax:

     splice ([array to modify], [offset],
     [length], [list of new elements]);

The array argument is the array to be manipulated. offset is the starting point where elements are to be removed. length is the number of elements from the offset number to be removed. The list argument consists of an ordered list of values to replace the removed elements with. Of course, if the list argument is null, the elements accessed will be removed rather than replaced.

Thus, for example, the following code will modify the @numbers list array to include the elements, ("1" , "2", "three", "four", "5").

     @numbers = ("1", "2", "3", "4", "5");
     splice (@numbers, 2, 2, "three", "four");

A more common usage of the splice is simply to remove list elements by not specifying a replacement list. For example, we might modify @numbers to include only the elements "1", "2" and "5" by using the following code:

     splice (@numbers, 2, 2);

Previous | Next | Table of Contents