Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Array lastIndexOf() method

JavaScript Array lastIndexOf() method

Array Object Reference JavaScript Array object

Example

Find the position where the array element "Apple" appears:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var a = fruits.lastIndexOf("Apple");

a Output result:

2

The output of the example above means that "Apple" is at the 2nd position in the array.

Try it »


Definition and Usage

The lastIndexOf() method returns the last position of a specified element in an array, searching from back to front.

If the element to be searched for does not appear, the method returns -1.

This method searches the array from end to beginning for the specified element item. The search starts at position start in the array or at the end of the array (when the start parameter is not specified). If an item is found, it returns the position of the first occurrence of the item when searching from the end. Array indexing starts at 0.

If the specified element is not found in the array, it returns -1.

Tip: If you want to find the first occurrence position in the array, use the indexOf() method.


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the lastIndexOf() property, but Internet Explorer 8 and earlier IE versions do not support this method.


Syntax

array

.lastIndexOf(

item

,

start

)

Parameter Values

Parameters Description
item Required. Specifies the string value to search for.
start Optional integer parameter. Specifies the position in the string where the search begins. Its valid range is 0 to stringObject.length - 1. If this parameter is omitted, the search starts from the last character of the string.

Return Value

Type Description
Number If searchvalue exists before the fromindex position in stringObject, the position of the last occurrence of searchvalue is returned.

Technical Details

JavaScript version: 1.6

More examples

Example

Find the position of "Apple" in the array:

var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];

var a = fruits.lastIndexOf("Apple");

a Output result:

6

Try it »

Example

Find the position of the string "Apple" starting from the fourth position in the array:

var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];

var a = fruits.lastIndexOf("Apple",4);

a Result output:

2

Try it »


Array Object Reference JavaScript Array object