HTML and CSS Reference
In-Depth Information
with new ones. (Don't confuse this method with the slice() method. The slice()
method copies elements, the splice() method removes and/or replaces elements.
Ropes, tapes, and films are spliced; bread, meat, and golf balls are sliced.)
FORMAT
Arrayname.splice(index position, number of elements to remove);
Arrayname.splice(index position, number of elements to remove,
replacement elements);
EXAMPLE
myArray.splice(3, 2);
myArray.splice(3, 2, "apples","oranges");
EXAMPLE 9.15
<html>
<head><title>Array splice() method</title></head>
<body>
<script type="text/javascript">
// splice(starting_pos, number_to_delete, new_values)
1
var names=new Array("Tom","Dan", "Liz", "Jody");
document.write("<b>Original array: "+ names + "<br />");
2
names.splice(1, 2, "Peter","Paul","Mary");
3
document.write("New array: "+ names + "</b>");
</script>
</body>
</html>
EXPLANATION
1
An Array object called names is declared and initialized.
2
The splice() method allows you to delete elements from an array and optionally re-
place the deleted elements with new values. The first arguments to the splice meth-
od are 1, 2 . This means: start at element 1, and remove a length of 2 elements. In
this example, element 1 starts with “Dan” (element 0 is “Tom” ). “Liz” is the second
element. Both “Dan” and “Liz” are removed. The next three arguments, “Peter” ,
“Paul” , and “Mary” , are then inserted into the array, replacing “Dan” and “Liz” .
3
The new names array is displayed in the browser window (see Figure 9.18).
Figure 9.18 The splice() method to delete and insert elements of an array.
 
Search WWH ::




Custom Search