Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • slice() method of the JavaScript Array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 239
    Comment on it

    JavaScript Array slice() method : The slice() method is used to get the elements between two position. The slice() method returns the array of extracted elements. It doesn't change the original array. The index starts from 0.


    Syntax of the Array slice() method :

    array.slice(start,end)
    

    start : Required. This is the numeric value from where to start the extract elements. To count from end use the negative value.

    end : Optional. This is the numeric value where end the extraction. It will omit the last value.


    Example of Array slice() method : Here I will show how to extract the elements between two indexes of the array. The first sample will extract all the elements starts from 2nd position to end.

    Sample1.html

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>To extract all the elements starts from Third element from the array, click the button "extract elements".</p>
    <button onclick="extractElements()">extract elements</button>
    <p id="container"></p>
    
    <script>
    function extractElements() {
        var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Pramod"];
        var result = students.slice(2);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    

    Output :

    Rajesh, Pankaj, Sumit, Manish, Pramod
    


    Sample2.html

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>To extract all the elements starts from Third element to 5th element from the array, click the button "extract elements".</p>
    <button onclick="extractElements()">extract elements</button>
    <p id="container"></p>
    
    <script>
    function extractElements() {
        var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Pramod"];
        var result = students.slice(2, 5);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    

    Output :

    Rajesh,Pankaj,Sumit
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: