JavaScript Array indexOf()Method
Example
Find the "Apple" element in the array:
aResult output:
The output above means that the "Apple" element is located at the 3rd position in the array.
Try it Yourself »Definition and Usage
The indexOf() method returns the position of a specified element in an array.
The method searches the array from beginning to end to see if it contains the corresponding element. The search starts at the start position in the array, or at the beginning of the array (when no start parameter is specified). If an item is found, it returns the position of the first occurrence of the item. The starting position index is 0.
If the specified element is not found in the array, -1 is returned.
TipIf you want to find the last occurrence of a string, use thelastIndexOf() method。
Browser Support
![]()
![]()
![]()
![]()
![]()
All major browsers support the indexOf() method, but Internet Explorer 8 and earlier IE versions do not support this method.
Syntax
Parameter Values
| Parameter | Description |
|---|---|
| item | Required. The element to search for. |
| start | Optional integer parameter. Specifies the position in the array to start the search. Its valid values are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the first character of the string. |
Return Value
| Type | Description |
|---|---|
| Number | The position of the element in the array, or -1 if it is not found. |
Technical Details
| JavaScript Version: | 1.6 |
|---|
More Examples
Example
Find the "Apple" element in the array, starting the search at the fourth position of the array:
var a = fruits.indexOf("Apple",4);
aResult output:
Try it Yourself »
Other Extensions
JavaScript Array Object