Latest web development tutorials

JavaScript indexOf () method

Array Object Reference JavaScript Array Object

Examples

Find an array of "Apple" elements:

var fruits = [ "Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf ( "Apple");

a result output:

2

The above output means that "Apple" in the array element at the second position.

try it"

Definition and Usage

indexOf () method returns the position of a string value of the first occurrence of the specified string.

This method will retrieve a string from start to finish stringObject, to see if it contains a substring searchvalue. Start retrieving location (not specified fromindex time) at the beginning or at the fromindex string string. If you find a searchvalue, the position of the first occurrence of searchvalue is returned. stringObject character position is zero-based.

If you did not find the string in the array or -1.

Tip If you want to find the last occurrence of the string, use lastIndexOf () method .


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support indexOf () method, but Internet Explorer 8 and earlier versions of IE does not support this method.


grammar

array .indexOf (item, start)

Parameter Value

参数 描述
item 必须。查找的元素。
start 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

return value

类型 描述
Number 元素在数组中的位置,如果没与搜索到则返回 -1

technical details

JavaScript version: 1.6


More examples

Examples

Find an array "Apple" element in the fourth position of the array began to Search:

var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.indexOf("Apple",4);

a result output:

6

try it"

Array Object Reference JavaScript Array Object