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

Hàm array findIndex () trong JavaScript

Hàm findIndex () trong JavaScript trả về chỉ mục của giá trị phần tử đầu tiên đáp ứng một điều kiện nhất định trong một mảng.

Sau đây là mã cho hàm find () mảng -

Ví dụ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .findIndex {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Array FindIndex() example</h1>
<div class="findIndex"></div>
<button class="findArr">CLICK HERE</button>
<h3>Click on the above button to get the index of lion in the array</h3>
<script>
   function findLion(animal) {
      return animal === "lion";
   }
   let fillEle = document.querySelector(".findIndex");
   let arr = ["cow", "lion", "bull", "tiger"];
   fillEle.innerHTML = arr;
   document.querySelector(".findArr").addEventListener("click", () => {
      fillEle.innerHTML = arr.findIndex(findLion);
   });
</script>
</body>
</html>

Đầu ra

Hàm array findIndex () trong JavaScript

Khi nhấp vào nút ‘BẤM VÀO ĐÂY’, chỉ mục của con sư tử sẽ được trả về như sau -

Hàm array findIndex () trong JavaScript