要查找任何元素的索引,请indexOf()
使用方法。以下示例给出了给定数组中特定元素的索引(solarCity)。
<html> <body> <p id="index"></p> <script> var companies = ["Spacex", "Tesla", "SolarCity", "Neuralika"]; var res = companies.indexOf("SolarCity"); document.getElementById("index").innerHTML = res; </script> </body> </html>
2
此方法还有助于在给定的指定索引之后查找元素的索引。下面的示例不是从开始而是从给定的指定索引4搜索特定元素“ solarCity”的索引。因此,索引为6,但不是2。
<html> <body> <p id="index"></p> <script> var companies = ["Spacex", "Tesla", "SolarCity", "Neuralika", "Spacex", "Tesla", "SolarCity", "Neuralika"]; var res = companies.indexOf("SolarCity", 4); document.getElementById("index").innerHTML = res; </script> </body> </html>
6