JavaScript Array indexOf()
Method
Example
Find the "Apple" element in the array:
a Output result:
The above output result indicates that the "Apple" element is located at the 3rd position in the array.
Definition and Usage
The indexOf()
method returns the position of a specified element in the array.
This method searches the array from the beginning to the end to see if it contains the corresponding element. The starting position of the search is at the start
of the array or at the beginning of the array (when the start
parameter is not specified). If an item is found, it returns the first occurrence of the item. The starting index is 0.
If the specified element is not found in the array, it returns -1.
Tip If you want to find the last occurrence of a string, use the lastIndexOf() method.
Browser Support
All major browsers support the indexOf()
method, but it is not supported in Internet Explorer 8 and earlier versions.
Syntax
Parameter Values
Parameter | Description |
---|---|
item | Required. The element to find. |
start | Optional integer parameter. Specifies the position in the array at which to start the search. Its valid range is from 0 to stringObject.length - 1. If 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 4th position:
a Output result: