JavaScript - Array find() 方法



在 JavaScript 中,Array.find() 方法對陣列中的每個元素執行一個回撥函式,並檢索滿足回撥函式指定條件的陣列中的第一個元素。

如果陣列元素不滿足特定條件,則此方法返回“undefined”。它不會對空陣列元素執行函式。此方法不會更改原始陣列。

findIndex() 和 find() 方法之間的區別在於;findIndex() 方法返回滿足測試函式的元素的第一個索引位置(而不是元素值)。

語法

以下是 JavaScript Array find() 方法的語法 -

array.find(callbackFn (element, index, array), thisArg);

引數

此方法接受兩個引數。下面描述了相同的內容 -

  • callbackfn - 這是一個回撥函式,將為陣列中的每個元素呼叫一次。它進一步接受三個引數
    • element - 陣列中正在處理的當前元素。
    • index - 正在處理的當前元素的索引。
    • array - 當前元素的陣列。
  • thisArg (可選) - 它指定傳遞給函式的值,用作其this 值。

返回值

此方法返回陣列中第一個滿足提供的測試函式的元素;否則,返回“undefined”。

示例

示例 1

在下面的示例中,我們使用 JavaScript Array find() 方法來查詢陣列元素中第一個大於 10 的元素 -

<html>
<body>
   <script>
      const numbers = [10, 23, 12, 43, 68];

      const result = numbers.find(function(element) {
         return element > 10;
      });
      document.write(result);
   </script>
</body>
</html>

輸出

上面的程式返回 23 作為輸出,因為它是在陣列元素中第一個大於 10 的元素。5

23

示例 2

在這裡,我們正在查詢“animals”陣列中長度大於 5 的第一個元素 -

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
      const result = animals.find(func => func.length > 5);
      document.write(result);
   </script>
</body>
</html>

輸出

Cheetah

示例 3

在這裡,我們使用 find() 方法和一個物件陣列來選擇 players 中的第一個專案(年齡大於 40) -

<html>
<body>
   <script>
      const players = [
         { name: 'Kohli', age: 35 },
         { name: 'Ponting', age: 48 },
         { name: 'Sachin', age: 50 }
      ];
      
      const result = players.find(item => item.age > 40);
      document.write(JSON.stringify(result));
   </script>
</body>
</html>

輸出

{"name":"Ponting","age":48}
廣告