JavaScript 中的 Array findIndex() 函式


JavaScript 中的 findIndex() 函式返回陣列中第一個滿足給定條件的元素值。

以下為陣列 find() 函式的程式碼 −

示例

 即時演示

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

輸出

點選 “點選這裡” 按鈕後,將如下所示返回獅子所在的索引 −

更新於: 2020 年 5 月 8 日

1000+ 瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.