JavaScript 数组 findIndex() 函数


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>

输出

点击“Result”以获取索引 −

示例

 实时演示

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

输出

上方,点击“Result”按钮 −

更新于: 17-12-2019

471 次浏览

职业生涯开始

完成课程,获得认证

开始
广告
© . All rights reserved.