JavaScript Array indexOf() Method
Example
Find the "Apple" element in the array:
var
fruits
=
[
"
Banana
"
,
"
Orange
"
,
"
Apple
"
,
"
Mango
"
]
;
var
a
=
fruits
.
indexOf
(
"
Apple
"
)
;
a Result output:
2
The output above means that the "Apple" element is at the 3rd position in the array.
Try it »
Definition and Usage
The indexOf() method returns the position of a specified element in an array.
This method searches the array from beginning to end to see whether it contains the corresponding element. The search starts at position start in the array, or at the beginning of the array (when the start parameter is not specified). If an item is found, it returns the index of the first occurrence of the item. The starting index is 0.
If the specified element is not found in the array, it returns -1.
TipIf you want to find the last occurrence of a string, use the lastIndexOf() method.
Browser support





All major browsers support the indexOf() method, but Internet Explorer 8 and earlier IE versions do not support this method.
Syntax
array
.indexOf(
item
,
start
)
Parameter value
| Parameters | Description |
|---|---|
| item | Required. The element to search for. |
| start | Optional integer parameter. Specifies the position in the array where the search begins. Its valid range is 0 to stringObject.length - 1. If this parameter is omitted, the search starts from the first character of the string. |
Return Value
| Type | Description |
|---|---|
| Number | The position of the element in the array, or -1 if not found. |
Technical Details
| JavaScript version: | 1.6 |
|---|
More examples
Example
Find the "Apple" element in the array, starting the search from the fourth position of the array:
var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.indexOf("Apple",4);
a Result output:
6
Try it »
JavaScript Array object