Javascript IndexOf() Function

The indexof() function of array object returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. Use it for example to find element in the array.

Syntax

arr.indexOf(searchElement[, fromIndex])

Javascript IndexOf() Function Example1

<DOCTYPE html>
<html> 
<head> 
<script type="text/javascript">
var arr = [1, 2, 6,10,22,12,38,100];
document.write(arr.indexOf(2) + "<br/>");
document.write(arr.indexOf(3) + "<br/>");
document.write(arr.indexOf(2, -1) + "<br/>");
document.write(arr.indexOf(2, -3) + "<br/>");
document.write(arr.indexOf(10, 3) + "<br/>");
</script>
</head>
<body>
</body>
</html>

Javascript IndexOf() Function Example2

<DOCTYPE html>
<html> 
<head> 
<script type="text/javascript">
// Create an array.
var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "def"];

// Find the first location of "def".
document.write(arr.indexOf("def") + "</br>");

// Find "def" starting at index 2.
document.write(arr.indexOf("def", 4) + "</br>");

// Find "xyz" (which is not found).
document.write (arr.indexOf("xyz")+ "</br>");
</script>
</head>
<body>
</body>
</html>