JS Array index

Array indexOf()

The JavaScript Array indexOf() Method is used to find the index of the first occurrence of the search element provided as the argument to the method. This method always compares the search element to the element present in the array using strict equality. Therefore, when the search element is NaN then it returns -1 because NaN values are never compared as equal.

Syntax:

array.indexOf(element, start)


Parameters: This method accepts two parameters as mentioned above and described below: 

Return value: This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.
 

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Sanjay", "Aman", "Rehman", "Aman", "Rahul"];
    document.write(a + "<br><br>");
    var b = a.indexOf("Aman",2);
    document.write(b);
  </script>
</head>
<body>
</body>
</html>

Array lastIndexOf()

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Sanjay", "Aman", "Rehman", "Aman", "Rahul"];
    document.write(a + "<br><br>");
    var c = a.lastIndexOf("Aman");
    document.write(c + "<br><br>");
  </script>
</head>
<body>
</body>
</html>