JavaScript Array indexOf()
- Previous Page includes()
- Next Page isArray()
- Go Back to the Previous Level JavaScript Array Reference Manual
Definition and Usage
indexOf()
The method searches for the specified item in the array and returns its position.
The search starts from the specified position, if no starting position is specified, it starts from the beginning, and ends at the end of the array.
If the item is not found, then indexOf()
returns -1.
If the item appears multiple times, then indexOf()
The method returns the position of the first occurrence.
Note:The position of the first item is 0, the position of the second item is 1, and so on.
Tip:If you want to search from the end to the beginning, use lastIndexOf()
Method.
Example
Example 1
Search for the item "Apple" in the array:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple");
Example 2
Search for the item "Apple" in the array, starting from position 4:
var fruits = ["Banana", "Orange", "Apple", "Mango", "Banana", "Orange", "Apple"]; var a = fruits.indexOf("Apple", 4);
Syntax
array.indexOf(item, start)
Parameter Value
Parameter | Description |
---|---|
item | Required. The item to search for. |
start | Optional. The position where to start the search. Negative values indicate positions counted from the end, then search to the last. |
Technical Details
Return Value: | A number, representing the position of the specified item, otherwise -1. |
---|---|
JavaScript Version: | ECMAScript 5 |
Browser Support
All browsers fully support indexOf()
Method:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Supported | 9.0 | Supported | Supported | Supported | Supported |
Related Pages
Tutorial:JavaScript Array
Tutorial:JavaScript Array Const
Tutorial:JavaScript Array Methods
Tutorial:JavaScript Array Sorting
Tutorial:JavaScript Array Iteration
Manual:Array lastIndexOf Method
- Previous Page includes()
- Next Page isArray()
- Go Back to the Previous Level JavaScript Array Reference Manual