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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 117
    Comment on it

    JavaScript Array indexOf() method : The indexOf() method is used to return the position of the any given element inside the array. It returns the numeric value and if element not found in that array then it returns the -1. The index is starts from the 0. If any element exists more then once in array then indexOf() function returns the position of first occurance of the element .


    Syntax of the indexOf() method in JavaScript :

    array.indexOf(element, start)
    

    element : Required. This is the element for which we need to know the position.

    start : Optional. This parameter is used when we need to search the element from specified position. This is the index from where the search starts for element.


    Example of the Array indexOf() method in JavaScript : Following is the sample example in which I will show you how to use the indexOf() method of array to know the position of the element inside the array.

    Sample.htlml

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>To display the position of the element "Pankaj", click the button "show index".</p>
    <button onclick="showIndex()">show index</button>
    <p id="container"></p>
    
    <script>
    function showIndex() {
        var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit"];
        var result = students.indexOf("Pankaj");
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    

    Output :

    3
    

 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: