Javascript examples for Array:indexOf
The indexOf() method searches the array for the specified item, and returns its position.
If the item is present more than once, the indexOf method returns the position of the first occurrence.
The first item has position 0, the second item has position 1, and so on.
array.indexOf(item, start)
Parameter | Description |
---|---|
item | Required. The item to search for |
start | Optional. Where to start the search. |
Negative values will start counting from the end, and search to the end.
A Number, representing the position of the specified item, otherwise -1
The following code shows how to Search an array for the item "e":
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {/*from www. ja va 2 s . com*/ var fruits = ["a","b","c","d","e", "a","b","c","d","e"]; var a = fruits.indexOf("e", 4); document.getElementById("demo").innerHTML = a; } </script> </body> </html>