Array.indexOf Function

Searches for the specified element of an Array object and returns its index. This function is static and can be invoked without creating an instance of the object.

var indexVar = Array.indexOf(array, item, start);

Arguments

Term

Definition

array

The array to search.

item

The object to find in the array.

startIndex

(Optional) The index number that specifies the starting element for searching the array.

Returns

A number that represents the index location of item in the array, if found; otherwise, -1.

In Mozilla Firefox, calling indexOf with item not set or set to undefined returns the index of the first item with a value of undefined. All other browsers return -1 in these circumstances.

Remarks

Use the indexOf function to determine the index location of the first occurrence of an element in an array instance.

Example

The following example shows how to find the index location of a specified item using the indexOf function. The index returned is the first occurrence of the item specified in item. You can find the next occurrence of item by calling the function again and specifying a starting index value larger than the index of the found element.

var a = ['red', 'blue', 'green', 'blue'];
var myFirstIndex = Array.indexOf(a, "blue");
// View the results: "1"
alert("myFirstIndex: " + myFirstIndex);
var mySecondIndex = Array.indexOf(a, "blue", (myFirstIndex + 1) );
// View the results: "3"
alert("mySecondIndex: " + mySecondIndex);

See Also

Reference

Array Object

Array Type Extensions

Other Resources

Language Reference