JavaScript indexOf() method


JavaScript indexOf() Method

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网</title>
</head>
<body>

<p id="demo">单击按钮显示“苹果”的位置:</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var fruits = ["香蕉", "橙子", "苹果", "甜瓜"];
	var a = fruits.indexOf("苹果")
	var x=document.getElementById("demo");
	x.innerHTML=a;
}
</script>
<p><b>注意:</b>indexOf方法是在JavaScript 1.6中引入的,在IE 8或更早的版本中不可用。</p>

</body>
</html>

Run Instance»

Click the "Run Example" button to view the online example


Definition and usage

indexOf() method can return the first time a specified string value is found in the string The location where it appears.

This method will retrieve the string stringObject from beginning to end to see if it contains the substring searchvalue. The starting position of the search is at the fromindex of the string or the beginning of the string (when fromindex is not specified). If a searchvalue is found, the position of the first occurrence of searchvalue is returned. Character positions in stringObject start from 0.

If the string is not found in the array, -1 is returned.

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


Browser support

QQ截图20161108165429.png

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


Syntax

##array.indexOf(item,start)
Parameter value

ParameterDescriptionmust. The element to find. Optional integer parameter. Specifies the position in the string to begin searching. Its legal values ​​are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the first character of the string.
item
start
Return value

TypeDescriptionNumberThe position of the element in the array, if not found, it returns -1##Technical details

JavaScript Version:
1.6
##More Examples

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网</title>
</head>
<body>

<p id="demo">单击按钮显示从位置4开始查找的“苹果”第一次出现的位置:</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple","Mango"];
	var a=fruits.indexOf("Apple",4)
	var x=document.getElementById("demo");
	x.innerHTML=a;
}
</script>
<p><b>注意:</b>indexOf方法是在JavaScript 1.6中被引进的,在IE 8 或更早的版本中不支持。 </p>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance