Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

JavaScript Array findIndex() function

Phương thức findIndex() của JavaScript dùng để trả về chỉ số của phần tử đầu tiên trong mảng thỏa mãn điều kiện.

Cú pháp:

array.findIndex(function(currentValue, index, arr), thisValue)

Triển khai findIndex() trong JavaScript:

Ví dụ 1

<!DOCTYPE html>
<html>
<body>
  <h2>Rank</h2>
  <button onclick="display()">Result</button>
  <p id="demo"></p>
  <p>Finding the index of the player with highest rank.</p>
  <script>
    var points = [100, 150, 200, 250, 300, 400];
    function topRank(points) {
      return points >= 400;
    }
    function display() {
      document.getElementById("demo").innerHTML = "index = " + points.findIndex(topRank);
    }
  </script>
</body>

Kết quả

JavaScript Array findIndex() function

Click "Result" để lấy index –

JavaScript Array findIndex() function

Ví dụ 2

<!DOCTYPE html>
<html>
<body>
  <h2>Rank</h2>
  <button onclick="display()">Result</button>
  <p id="demo"></p>
  <p>Finding the index of the player with specific rank points.</p>
  <script>
    var points = [100, 150, 200, 250, 300, 400];
    function topRank(points) {
      return points == 200;
    }
    function display() {
      document.getElementById("demo").innerHTML = "index = " + points.findIndex(topRank);
    }
  </script>
</body>

Kết quả

JavaScript Array findIndex() function

Click nút "Result" –

JavaScript Array findIndex() function