Searching Arrays with indexOf and lastIndexOf
Syntax
lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex)
Parameters
searchElement
-
Element to locate in the array.
fromIndex
Optional-
Zero-based index at which to start searching backwards, converted to an integer.
- Negative index counts back from the end of the array - if
fromIndex < 0
,fromIndex + array.length
is used. - If
fromIndex < -array.length
, the array is not searched and-1
is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, sosearchElement
is never found. - If
fromIndex >= array.length
orfromIndex
is omitted,array.length - 1
is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.
- Negative index counts back from the end of the array - if
Return value
The last index of the element in the array; -1 if not found.