Return to Kroll Design home page

JavaScript - splice method for arrays

 
« Return

The splice method for arrays removes elements from an array, and if desired, replaces those removed elements with new elements that you specify.

The first parameter is the element number of the first cell to remove or replace.
The second parameter is how many elements you want to remove or replace.
If you want to replace array elements instead of remove them, include the new array values as additional parameters.

Code:

<script type="text/javascript">
//<![CDATA[
myArray = new Array("Happy", "birthday", "one", "two", "three", "you"); document.write("<br>myArray before being spliced:<br>"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br>"); } myArray.splice(3,2); document.write("<br>myArray after being spliced:<br>"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br>"); } myArray.splice(2, 1, "to"); document.write("<br>myArray after being spliced again, this time with a replacement element:<br>"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br>"); } //]]> </script>

Output:



 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM