JavaScript 五四三 Ep.05 Array.prototype.find()


Posted by ABow_Chen on 2022-09-26

一、find() 簡介

  1. 對陣列使用 find() 方法,會回傳滿足函式條件的第一個值,否則便回傳 undefined。
  2. 不會改變原陣列。
  3. 若使用 find() 的原陣列是一個稀疏陣列(sparse array,即某些索引位置留空),find() 方法仍會將所有索引位置帶進函式中,即使某些索引位置是沒有賦值的,因此 find() 在處理稀疏陣列上的效能可能會比其他只存取已賦值索引的方法來得差。

二、find() 語法

arr.find(callback(element, index, array) {}, thisArg)

callback: 這個 callback 函式,會把陣列中的每一個元素當成參數,帶入 callback 函式中,經過函式運算後,符合條件(true)的第一個值會被回傳,若無符合條件(false)的值,則回傳 undefined,可傳入三個參數:

element: 目前被處理中的原陣列裡的元素。

index(選擇性): 上述元素的索引值。

array(選擇性): 使用 map() 的陣列本身,即上述語法中的 arr 。

thisArg:執行 callback 函式的 this 值(即參考的物件)。

語法的執行範例如下:

const arr = [1, 3, 5, 7, 9];
const arrFound = arr.find(function(num){
  return num > 5;
});
console.log(arrFound); // 7 雖然符合條件的有 7 跟 9,但只會回傳第一個符合條件的值

const arr = [1, 3, 5, 7, 9];
const arrFound = arr.find(function(num){
  return num > 10;
});
console.log(arrFound); // undefined 若沒有符合條件的值,則回傳 undefined

ES6 的寫法:

const arr = [1, 3, 5, 7, 9];
const arrFound = arr.find((num)=> num > 5);
console.log(arrFound); // 7

三、find() 常見用法

  1. 查找陣列中之物件符合條件的屬性

     const foods = [
     {name: 'pork', price: 120 },
     {name: 'steak', price: 180},
     {name: 'chicken steak', price: 80}
     ];
     const foodFound = foods.find((food)=> food.price < 100);
     console.log(foodFound); // {name: 'chicken steak', price: 80}
    

參考資料:

https://www.casper.tw/javascript/2017/06/29/es6-native-array/#Array-prototype-find

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/find


#javascript #find







Related Posts

ModernWeb'21 隨筆

ModernWeb'21 隨筆

AI輔導室|快速完成歪扭標準字

AI輔導室|快速完成歪扭標準字

極簡複習:函式和模組的 Python 程式範例

極簡複習:函式和模組的 Python 程式範例


Comments