JavaScript - Array slice() Method


Advertisements


Description

Javascript array slice() method extracts a section of an array and returns a new array.

Syntax

Its syntax is as follows −

array.slice( begin [,end] );

Parameter Details

  • begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence.

  • end − Zero-based index at which to end extraction.

Return Value

Returns the extracted array based on the passed parameters.

Example

Try the following example.

<html>
   <head>
      <title>JavaScript Array slice Method</title>
   </head>
   
   <body>
   
      <script type="text/javascript">
         var arr = ["orange", "mango", "banana", "sugar", "tea"];
         document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); 
         document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) ); 
      </script>
      
   </body>
</html>

Output

arr.slice( 1, 2) : mango
arr.slice( 1, 3) : mango,banana 

javascript_arrays_object.htm