Array in JavaScript has slice() method that is used to extract a section of an array. This method returns a new array.
Syntax is as below:
1 | array.slice( begin [,end] ); |
begin: Zero-based index at which to begin the extraction. As a negative index, start indicates an offset from the end of the sequence.
end: Optional, zero-based index at which to end the extraction.
Return Value:
slice() method returns the extracted array based on the passed parameters.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <html> <head> <title>Array in JavaScript - slice() Method</title> </head> <body> <script type="text/javascript"> var myArr = ["jQuery", "PHP", "HTML", "CSS", "WordPress"]; document.write("Array: " + myArr); document.write("<br /><br />arr.slice( 1, 2) : " + myArr.slice( 1, 2 )); document.write("<br /><br />arr.slice( 0, 3) : " + myArr.slice( 0, 3 )); </script> </body> </html> |
Output: This will give the following output:
1 2 3 4 5 | Array: jQuery,PHP,HTML,CSS,WordPress arr.slice( 1, 2) : PHP arr.slice( 0, 3) : jQuery,PHP,HTML |
To understand the slice() method in better way Try yourself.