Skip to main content

ES6 find、findIndex介紹

一、ES6 find 方法介紹

1. 什麼是 find?

  • find 是 ES6 引入的陣列方法,用來在陣列中尋找第一個符合條件的元素,並返回該元素的值。

  • 如果找不到符合條件的元素,find 會回傳 undefined。

  • 它接受一個回呼函式(callback function)作為參數,這個回呼函式會對陣列中的每個元素執行,直到找到第一個符合條件的元素為止。

2. 語法

array.find(callback(element[, index[, array]])[, thisArg])
  • callback: 回呼函式,會對陣列的每個元素執行,包含以下參數:

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

    • index(可選): 當前元素的索引。

    • array(可選): 正在操作的陣列本身。

  • thisArg(可選): 執行回呼函式時的 this 值。

  • 回傳值: 第一個符合條件的元素,若無則回傳 undefined。

3. 特點

  • 只返回第一個符合條件的元素,找到後立即停止遍歷。

  • 不會改變原始陣列。

  • 適用於尋找物件、數字、字串等任何類型的陣列元素。

4. 範例

假設你有一個使用者陣列,裡面包含多個物件,你想找到第一個年齡大於 25 歲的使用者:

const users = [
{ id: 1, name: "小明", age: 22 },
{ id: 2, name: "小華", age: 30 },
{ id: 3, name: "小強", age: 27 },
];

const user = users.find((item) => item.age > 25);
console.log(user); // 輸出: { id: 2, name: '小華', age: 30 }

二、ES6 findIndex 方法介紹

1. 什麼是 findIndex?

  • findIndex 與 find 類似,但它返回的是第一個符合條件的元素的索引值,而不是元素本身。

  • 如果找不到符合條件的元素,findIndex 會回傳 -1。

2. 語法

array.findIndex(callback(element[, index[, array]])[, thisArg])
  • 參數與 find 相同。

  • 回傳值: 第一個符合條件的元素的索引值,若無則回傳 -1。

3. 特點

  • 只返回第一個符合條件的元素的索引值,找到後立即停止遍歷。

  • 不會改變原始陣列。

  • 適用於需要知道元素位置的場景,例如更新或刪除陣列中的特定元素。

4. 範例

使用相同的使用者陣列,找到第一個年齡大於 25 歲的使用者的索引:

const users = [
{ id: 1, name: "小明", age: 22 },
{ id: 2, name: "小華", age: 30 },
{ id: 3, name: "小強", age: 27 },
];

const index = users.findIndex((item) => item.age > 25);
console.log(index); // 輸出: 1

三、在 React 中的實際應用

在 React 專案中,find 和 findIndex 常用來處理狀態(state)中的陣列資料,例如搜尋特定資料、更新資料或渲染特定內容。以下是一個完整的 React 範例,展示如何使用這兩個方法來實現搜尋功能。

範例:搜尋使用者並顯示結果

假設你有一個簡單的 React 組件,包含一個使用者列表,當使用者輸入 ID 時,顯示對應的使用者資訊或索引值。

import React, { useState } from "react";

function UserSearch() {
// 使用者資料陣列
const users = [
{ id: 1, name: "小明", age: 22 },
{ id: 2, name: "小華", age: 30 },
{ id: 3, name: "小強", age: 27 },
];

// 狀態管理:輸入的 ID、搜尋結果、索引值
const [searchId, setSearchId] = useState("");
const [foundUser, setFoundUser] = useState(null);
const [foundIndex, setFoundIndex] = useState(-1);

// 處理搜尋邏輯
const handleSearch = () => {
// 使用 find 找到符合 ID 的使用者
const user = users.find((user) => user.id === parseInt(searchId));
// 使用 findIndex 找到符合 ID 的索引
const index = users.findIndex((user) => user.id === parseInt(searchId));

setFoundUser(user);
setFoundIndex(index);
};

return (
<div style={{ padding: "20px" }}>
<h2>使用者搜尋</h2>
<input
type="number"
value={searchId}
onChange={(e) => setSearchId(e.target.value)}
placeholder="輸入使用者 ID"
/>
<button onClick={handleSearch}>搜尋</button>

<div>
{foundUser ? (
<p>
找到使用者:{foundUser.name},年齡:{foundUser.age}
</p>
) : (
<p>未找到符合的使用者</p>
)}
<p>索引值:{foundIndex !== -1 ? foundIndex : "無"}</p>
</div>

<h3>所有使用者</h3>
<ul>
{users.map((user) => (
<li key={user.id}>
ID: {user.id}, 姓名: {user.name}, 年齡: {user.age}
</li>
))}
</ul>
</div>
);
}

export default UserSearch;

程式碼說明

  1. 資料準備

    • 定義一個靜態的 users 陣列,包含多個使用者物件。
  2. 狀態管理

    • 使用 useState 管理輸入的 searchId(使用者輸入的 ID)、foundUser(搜尋到的使用者物件)、foundIndex(搜尋到的索引值)。
  3. 搜尋邏輯

    • 在 handleSearch 函式中,使用 find 尋找符合 ID 的使用者物件,並使用 findIndex 尋找對應的索引值。

    • 將結果儲存到狀態中,觸發組件重新渲染。

  4. UI 呈現

    • 提供一個輸入框讓使用者輸入 ID,按下「搜尋」按鈕後顯示結果。

    • 如果 foundUser 存在,顯示使用者的姓名和年齡;否則顯示「未找到」。

    • 顯示索引值,若 foundIndex 為 -1,則顯示「無」。

  5. 列表渲染

    • 使用 map 渲染所有使用者列表,確保每個 li 元素有唯一的 key。

四、find 與 findIndex 的使用場景

  1. React 中的常見場景

    • 資料篩選:從狀態中的陣列找出特定項目,例如根據 ID 或其他條件篩選資料。

    • 動態更新:使用 findIndex 找到要更新的項目索引,然後更新狀態中的陣列。

    • 條件渲染:根據 find 的結果決定是否渲染特定內容。

  2. 其他場景

    • 檢查陣列中是否包含某個特定值(find)。

    • 獲取某個元素的索引以進行刪除或替換(findIndex)。


五、注意事項

  1. 效能考量

    • find 和 findIndex 會遍歷陣列,直到找到第一個符合條件的元素。如果陣列非常大,應該考慮資料結構優化(例如使用物件或 Map 來加速查找)。
  2. 回傳值處理

    • find 可能回傳 undefined,使用前應檢查結果。

    • findIndex 回傳 -1 時,表示未找到,需妥善處理。

  3. 與其他方法的比較

    • 與 filter 的差異:filter 回傳所有符合條件的元素陣列,而 find 只回傳第一個元素。

    • 與 indexOf 的差異:indexOf 適用於簡單值(如數字或字串)的精確匹配,而 findIndex 支援複雜條件。


六、總結

  • find:用來取得第一個符合條件的元素,適合需要單一資料的場景。

  • findIndex:用來取得第一個符合條件的元素索引,適合需要操作陣列索引的場景。

  • 在 React 中,這兩個方法非常適合處理狀態中的陣列資料,特別是搜尋、篩選或更新資料時。