ES6 - Array.find 方法



此函式返回陣列中第一個滿足提供的測試函式的元素的值。否則返回 undefined。

語法

以下是陣列方法 find() 的語法,其中,thisArg 是一個可選物件,用作執行 callback 時的 this,callback 是在陣列中每個值上執行的函式,它接受以下三個引數:

  • element - 陣列中正在處理的當前元素。

  • index - 可選;指的是陣列中正在處理的當前元素的索引。

  • array - 可選;呼叫 find 的陣列。

arr.find(callback(element[, index[, array]])[, thisArg])

示例

<script>
   //find
   const products = [{name:'Books',quantity:10},
      {name:'Pen',quantity:20},
      {name:"Books",quantity:30}
   ]
   console.log( products.find(p=>p.name==="Books"))
</script>

上述程式碼的輸出如下所示:

{name: "Books", quantity: 10}
廣告

© . All rights reserved.