/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: indexOf()

[this page | pdf | back links]

The indexOf() method (when applied to a JavaScript array) returns the index of the first element of an array found when an array is searched.

 

It has the following syntax with the following parameters. It returns a number as above (or -1 if no array element passes the test).

 

array.indexOf(item, start)

 

Parameter

Required / Optional

Description

item

Required

Item to search for

start

Optional

Index value at which to start search. Negative values indicate start from a position counting back from the end and then search to the end

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var h = ["a","b","b"];
document.getElementById("Example").innerHTML =
  'var h = ["a","b","b"];<br>' +
  'var x = h.indexOf("b");';
document.getElementById("Result").innerHTML = h.indexOf("b");
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArrayIndexOf() {
  var h = [1, 2, 3]; return !!h.indexOf;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile