- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Array slice()
The slice() method of JavaScript is used to return the selected elements in an array.
The syntax is as follows −
array.slice(start, end)
Above, start parameter is an integer specifying where to begin the selection, whereas, end is where the selection ends.
Let us now implement the slice() method in JavaScript −
Example
<!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p id="test"></p> <script> var arr = ["Accessories", "Electronics", "Books", "Pet Supplies"]; document.getElementById("test").innerHTML = "Initial array = "+arr+", <br>Sliced = "+arr.slice(2, 4); </script> </body></html>
Output
Example
<!DOCTYPE html> <html> <body> <h2>Car Variant</h2> <button onclick="display()">Result</button> <p id="test"></p> <script> var car = ["Hatchback", "Convertible", "SUV", "AUV", "MUV"]; document.getElementById("test").innerHTML = "Initial Array = "+car; function display() { document.getElementById("test").innerHTML = "Array after slicing some elements = "+car.slice(1,4); } </script> </body></html>
Output
Click “Result” button −
Advertisements