Tech Junkie Blog: JavaScript Array Methods : indexOf() method

Monday, June 18, 2018

JavaScript Array Methods : indexOf() method

The indexOf() method searches for the element in the array that matches the passed in value.
In this example we will search for the value 60.50 in the array.  The indexOf() method takes two arguments.  The first argument is the value to search for, the second argument is optional and specifies the index to start the search at.  If the second argument is omitted the search will start at the first element of the array.

    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var searchAtBeginning = oilPrices.indexOf(60.50);

        var searchAtIndex = oilPrices.indexOf(60.50,2);

        console.log("searchAtBeginning: " + searchAtBeginning);
        console.log("searchAtIndex: " + searchAtIndex);
    </script>

Here is the output:







As you can see the first indexOf() method call returns the index of 1 because that's where 60.50 resides.  It was able to find the element because the second argument was omitted there the search starts at the beginning array.  The second indexOf() method call has the value of 2 as the second argument that tells the method start the search at index 2 in the array.  Since the value 60.50 exists at index 1, the method returns a -1 which means it cannot find the value.


No comments:

Post a Comment