Computer >> Máy Tính >  >> Lập trình >> Javascript

Viết chương trình tìm chỉ số của phần tử cụ thể trong mảng trong javascript?

indexOf ()

Để tìm chỉ mục của bất kỳ phần tử nào, phương thức indexOf () được sử dụng. Ví dụ sau cung cấp chỉ số của một phần tử cụ thể (SolarCity) từ một mảng nhất định.

Ví dụ

<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>

Đầu ra

2

Phương pháp này cũng giúp tìm chỉ mục của một phần tử sau một chỉ mục cụ thể nhất định. / P>

Ví dụ

<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>

Đầu ra

6