The indexOf()
method of Array
instances returns the first index at which a given element can be found in the array, or -1 if it is not present.
The indexOf()
method of Array
instances returns the first index at which a given element can be found in the array, or -1 if it is not present.
searchElement
Element to locate in the array.
fromIndex
Optional
Zero-based index at which to start searching, converted to an integer.
fromIndex < 0
, fromIndex + array.length
is used. Note, the array is still searched from front to back in this case.fromIndex < -array.length
or fromIndex
is omitted, 0
is used, causing the entire array to be searched.fromIndex >= array.length
, the array is not searched and -1
is returned.The first index of searchElement
in the array; -1
if not found.
The indexOf()
method compares searchElement
to elements of the array using strict equality (the same algorithm used by the ===
operator). NaN
values are never compared as equal, so indexOf()
always returns -1
when searchElement
is NaN
.
The indexOf()
method skips empty slots in sparse arrays.
The indexOf()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
function updateVegetablesCollection(veggies, veggie) { if (veggies.indexOf(veggie) === -1) { veggies.push(veggie); console.log(`New veggies collection is: ${veggies}`); } else { console.log(`${veggie} already exists in the veggies collection.`); } } const veggies = ["potato", "tomato", "chillies", "green-pepper"]; updateVegetablesCollection(veggies, "spinach"); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, "spinach"); // spinach already exists in the veggies collection.
The indexOf()
method reads the length
property of this
and then accesses each property whose key is a nonnegative integer less than length
.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
indexOf |
1 | 12 | 1.5 | 9.5 | 3 | 18 | 4 | 10.1 | 1 | 1.0 | ≤37 | 1.0 | 0.10.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf