Find the first index of "Apple":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let index = fruits.indexOf("Apple");
Try it Yourself »
Start at index 3:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
let index = fruits.indexOf("Apple", 3);
Try it Yourself »
More examples below.
The indexOf()
method returns the first index (position) of a specified value.
The indexOf()
method returns -1 if the value is not found.
The indexOf()
method starts at a specified index and searches from left to right.
By default the search starts at the first element and ends at the last.
Negative start values counts from the last element (but still searches from left to right).
The lastIndexOf()
method
array.indexOf(
item,
start)
Parameter | Description | |
item | Required. The value to search for. |
|
start | Optional. Where to start the search. Default value is 0. Negative values start the search from the end of the array. |
Type | Description |
A number | The index (position) of the first item found. -1 if the item is not found. |
In an array, the first element has index (position) 0, the second has index 1, ...
Find the first index of "Apple", starting from the last element:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
let index = fruits.indexOf("Apple", -1);
Try it Yourself »
indexOf()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!