Array indexOf() Method - Javascript Array

Javascript examples for Array:indexOf

Description

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.

Syntax

array.indexOf(item, start)

Parameter Values

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.

Return Value:

A Number, representing the position of the specified item, otherwise -1

The following code shows how to Search an array for the item "e":

Demo Code

ResultView the demo in separate window

<!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>

Related Tutorials