JavaScript 陣列 find() 函式


JavaScript 的 find() 方法用於返回陣列中的第一個元素值(如果條件透過的話),否則返回值是未定義的。語法如下所示 -

array.find(function(val, index, arr),thisValue)

其中,function 是一個與 val(當前元素值)相關的函式。index 是陣列索引,arr 是陣列。this 值引數是傳遞給函式的值。

示例

 線上演示

<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <p>Get the points (first element) above 400...</p>
   <button onclick="display()">Result</button>
   <p id="demo"></p>
   <script>
      var pointsArr = [50, 100, 200, 300, 400, 500, 600];
      function pointsFunc(points) {
         return points > 400;
      }
      function display() {
         document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
      }
   </script>
</body>
</html>

輸出

現在,點選 “結果” 按鈕 -

我們再看另一個示例,其中的結果將是未定義的 -

示例

 線上演示

<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <p>Get the points (first element) above 400...</p>
   <button onclick="display()">Result</button>
   <p id="demo"></p>
   <script>
      var pointsArr = [50, 100, 200, 300, 400];
      function pointsFunc(points) {
         return points > 400;
      }
      function display() {
         document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
      }
   </script>
</body>
</html>

輸出

現在,點選 “結果” 按鈕 -

更新於: 2019 年 12 月 17 日

256 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.