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.