English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
lastIndexOf()The method returns the first character index value of a character or string from right to left (from the position where the string appears last), and returns if there is no match-1(opposite of indexOf).
If the element is not found, it will return-1.
If the element exists multiple times, it will return the position of the last occurrence.
If you want to search from the beginning to the end, useindexOf()Method.
Note:For more information on the String method, seeString.lastIndexOf().
array.lastIndexOf(element, start)
var fruits = ['Banana', 'Mango', 'Apple', 'Orange', 'Apple']; fruits.lastIndexOf('Apple');// returns 4Test and see‹/›
The numbers in the table specify the first browser version that fully supports the lastIndexOf() method:
Method | |||||
lastIndexOf() | Is | Is | 34 | Is | 9 |
Parameter | Description |
---|---|
element | (Required) The element to locate in the array |
start | (Optional) The index to start searching for the element. The default value is (array.length-1) |
Return value: | The last index of the element in the array;-1(If not found) |
---|---|
JavaScript Version: | ECMAScript 5 |
Return the last position of the element 'Orange' in the position5Start searching (search backward):
var fruits = ['Banana', 'Mango', 'Apple', 'Orange', 'Guava', 'Apple', 'Orange']; fruits.lastIndexOf('Orange', 5);Test and see‹/›
If the given parameter is a value that does not exist in the array, it will return-1:
var fruits = ['Banana', 'Mango', 'Apple', 'Orange', 'Apple']; fruits.lastIndexOf('Beer');// returns -1Test and see‹/›
If the element exists multiple times, it will return the position of the last occurrence:
var nums = [1, 4, 2, 3, 4, 5, 5, 4, 5]); nums.lastIndexOf(4);Test and see‹/›