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.