Return to Kroll Design home page

JavaScript Tutorials

 
« Return

slice method for arrays

The slice method returns a new array containing a portion of your original array. The first parameter specifies the first element to use, and the optional second parameter specifies the element one after the last element to use. If no second parameter is specified, the entire rest of the array is used.

Code:

<script type="text/javascript">
//<![CDATA[
myArray = new Array("oldest", "older", "newer", "newest"); document.write("myArray before the slice method is applied:<br />"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br />"); } document.write("<br />"); var newArray = myArray.slice(1,3); document.write("newArray after the slice method is applied with parms of 1 and 3:<br />"); for (i=0; i<newArray.length; i++) { document.write("myArray[", i, "] : ", newArray[i], "<br />"); } document.write("<br />"); document.write("myArray after the slice method is applied (it's unchanged):<br />"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br />"); } document.write("<br />"); newArray = myArray.slice(1); document.write("newArray after the slice method is applied with a first parm of 1 no second parm:<br />"); for (i=0; i<newArray.length; i++) { document.write("myArray[", i, "] : ", newArray[i], "<br />"); } document.write("<br />"); newArray = myArray.slice(0); document.write("newArray after the slice method is applied with a first parm of 0 no second parm, just give you the original array:<br />"); for (i=0; i<newArray.length; i++) { document.write("myArray[", i, "] : ", newArray[i], "<br />"); } //]]> </script>

Output:



 
« Return


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