The indexOf() method searches the array for an item, and returns its position.
indexOf()
starts searching from the
front of the array.
indexOf()
returns the position of the item
in the array or -1 if the item isn't in the array.
An identity comparison is used during comparing.
To search from end to start, use the lastIndexOf() method.
The returned index is from 0. The first item has position 0, the second item has position 1, and so on.
indexOf() |
Yes | 9.0 | Yes | Yes | Yes |
Array indexOf() has the following syntax:
indexOf(item_To_Look_For, optional_Index_To_Start_With)
Parameter | Description |
---|---|
item_To_Look_For | Required. The item to search. |
optional_Index_To_Start_With | Optional. Where to start the search. Negative values starts from the end of the array, and search to the end. |
It returns a number representing the position, if not found it returns -1.
var numbers = [1,2,3,4,5,4,3,2,1];
console.log(numbers.indexOf(4)); //3
console.log(numbers.indexOf(4, 4)); //5
// w ww. j ava 2 s. c om
var person = { name: "JavaScript" };
var people = [{ name: "JavaScript" }];
var morePeople = [person];
console.log(people.indexOf(person)); //-1
The code above generates the following result.