编写程序来查找JavaScript中数组中特定元素的索引?
指数()
要查找任何元素的索引,请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
热门推荐
10 姐姐生日祝福语漂亮简短
11 生日祝福语贺卡文字简短
12 新婚过年祝福语大全简短
13 婚庆花篮祝福语简短大气
14 考试祝福语日文简短版
15 公司开年仪式祝福语简短
16 描写周末的祝福语简短
17 登上舞台祝福语大全简短
18 简短朋友旅行祝福语大全