JavaScript 数组 findIndex() 函数

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/8/14 13:32:17

JavaScript 的 findIndex() 方法用于返回数组中第一个元素的索引(如果条件通过)。

语法如下 −

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

现在让我们在 JavaScript 中实现 findIndex() 方法 −

示例

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

输出

点击“结果”获取索引 −

示例

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

输出

点击上面的"结果"按钮 −


相关文章


有用资源