1. 簡介
JavaScript 是網頁開發中最廣泛使用的程式語言之一。特別是其陣列操作功能,在資料管理和使用者互動中扮演關鍵角色。 在本文中,我們詳細說明如何在 JavaScript 中搜尋陣列內的值。從基本搜尋方法到更進階的技巧,本指南為初學者和中級開發者提供有用的資訊。
本文目的
閱讀本文,您將學到以下要點:
- 了解用於陣列搜尋的主要 JavaScript 方法之間的差異。
- 透過程式碼範例學習每個方法的具體用法。
- 根據情境選擇適當的方法。
目標讀者
本文針對以下對象:
- 剛開始使用 JavaScript 的初學者。
- 希望加深對陣列搜尋和資料處理理解的中級使用者。
- 尋找實用程式碼範例的網頁開發者。
您將獲得的知識與技能
- JavaScript 陣列搜尋方法(
indexOf()、includes()、find()、findIndex())的基本知識和應用。 - 如何使用 jQuery 的
inArray()方法及其注意事項。 - 效能比較和實際使用情境。
掌握這些技能後,您將能夠更有效地使用 JavaScript 進行資料操作。
下一篇文章
下一篇文章中,我們將詳細說明「JavaScript 中的基本陣列搜尋方法」。我們將涵蓋每個方法的特性和用法,並提供具體範例。敬請期待。 如果您對本內容有任何問題或要求,請隨時聯繫。
2. JavaScript 中的基本陣列搜尋方法
JavaScript 提供了各種方法來搜尋陣列內的值。本節將以易懂的範例說明每個方法如何運作。
2-1. indexOf() 方法
概述 indexOf() 方法會傳回指定值在陣列中首次出現的索引。如果值不存在,則傳回 -1。 基本語法
array.indexOf(value, fromIndex)
- value : 要搜尋的值。
- fromIndex : 選用。搜尋的起始位置(預設為 0)。
範例
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('grape')); // Output: -1
注意事項
indexOf()使用嚴格相等(===)來比較值。不同類型的值不會匹配。- 不適合用來比較物件或陣列本身。
2-2. includes() 方法
概述 includes() 方法會傳回一個布林值(true 或 false),表示指定值是否存在於陣列中。 基本語法
array.includes(value, fromIndex)
範例
const colors = ['red', 'green', 'blue'];
console.log(colors.includes('green')); // Output: true
console.log(colors.includes('yellow')); // Output: false
注意事項
includes()是 ES6 (2015) 引入的,因此舊版瀏覽器可能不支援。
2-3. find() 方法
概述 find() 方法會傳回符合指定條件的第一个元素。如果沒有元素符合條件,則傳回 undefined。 範例
const numbers = [10, 20, 30, 40];
const result = numbers.find(num => num > 25);
console.log(result); // Output: 30
2-4. findIndex() 方法
概述 findIndex() 方法會傳回符合指定條件的第一个元素的索引。如果沒有符合條件的元素,則傳回 -1。 範例
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(num => num > 25);
console.log(index); // Output: 2
總結
本節說明了 JavaScript 的基本陣列搜尋方法:indexOf()、includes()、find() 和 findIndex()。 比較要點
- 對於簡單的值搜尋,使用
indexOf()或includes()。 - 對於條件搜尋,
find()或findIndex()很有用。

3. jQuery 的 inArray() 方法是什麼?
雖然 JavaScript 提供了原生陣列搜尋方法,jQuery 也提供了自己的方法 inArray()。本節說明其特徵、使用方式和注意事項。
3-1. 為什麼使用 jQuery?
jQuery 長期以來用於簡化 DOM 操作和事件處理。它仍然用於:
- 舊系統維護
- 簡化程式碼撰寫
- 與舊版瀏覽器的相容性
3-2. 如何使用 inArray()
Overview inArray() 會在陣列中返回值的索引。如果值不存在,則返回 -1。 Basic Syntax
$.inArray(value, array, [fromIndex])
Example
const fruits = ['apple', 'banana', 'orange'];
console.log($.inArray('banana', fruits)); // Output: 1
console.log($.inArray('grape', fruits)); // Output: -1
3-3. 比較:inArray() 與原生方法
| Feature | jQuery inArray() | JavaScript indexOf() |
|---|---|---|
| Environment | Requires jQuery | Native (no library needed) |
| Comparison Method | Strict equality (===) | Strict equality (===) |
| Performance | Slower (library overhead) | Fast (native) |
| Legacy Support | Strong | Some limitations in older browsers |
Key Points:
- 在 jQuery 專案中,為了一致性使用
inArray()。 - 在現代專案中使用原生方法。
3-4. 注意事項
1. jQuery 版本依賴 inArray() 僅在 jQuery 環境中運作。 2. 嚴格比較 它使用嚴格等式 (===) 來比較值。 3. 效能差異 原生方法更快。
Summary
本節涵蓋了 jQuery 的 inArray()。 Key Points:
- 對於舊版或基於 jQuery 的系統很方便。
- 建議在新開發中使用原生方法。
4. 選擇陣列搜尋方法的比較指南
JavaScript 和 jQuery 提供了多種陣列搜尋方法,每種都有不同的特徵和使用情境。本節比較主要方法,並說明根據您的情境如何選擇正確的方法。
4-1. 各方法的特徵與比較
以下是主要陣列搜尋方法的比較表格。
| Method Name | Result | Type Checking | Performance | Supported Environment | Features & Use Cases |
|---|---|---|---|---|---|
| indexOf() | Index number | Strict equality | Fast | ES5+ | Suitable for simple searches; cannot perform conditional searches. |
| includes() | Boolean (true/false) | Strict equality | Fast | ES6+ | Useful for simple existence checks. |
| find() | First matching element | Customizable | Medium | ES6+ | Strong for conditional searches using functions. |
| findIndex() | Index of first matching element | Customizable | Medium | ES6+ | Helps when you need the index of a condition match. |
| inArray() | Index number | Strict equality | Slow | jQuery only | Useful in legacy or jQuery-based systems. |
4-2. 依使用情境推薦的方法
1. 簡單值搜尋 範例:檢查陣列是否包含特定值。
- 推薦方法:
indexOf()→ 需要索引號碼時。includes()→ 簡單存在檢查就足夠時。
Example:
const colors = ['red', 'green', 'blue'];
console.log(colors.indexOf('green')); // Output: 1
console.log(colors.includes('green')); // Output: true
2. 條件搜尋 範例:搜尋符合特定條件的資料。
- 推薦方法:
find()→ 擷取第一個符合的元素。findIndex()→ 擷取第一個符合元素的索引。
Example:
const numbers = [10, 20, 30, 40];
console.log(numbers.find(num => num > 25)); // Output: 30
console.log(numbers.findIndex(num => num > 25)); // Output: 2
3. 舊系統搜尋 範例:在舊版基於 jQuery 的系統中搜尋資料。
- 推薦方法:
inArray()→ 需要 jQuery 時很有用。
Example:
const fruits = ['apple', 'banana', 'orange'];
console.log($.inArray('banana', fruits)); // Output: 1
4-3. 效能比較
1. 需要高速時:
indexOf()和includes()很快。
2. 條件搜尋時:
find()和findIndex()允許靈活條件,但稍慢。
3. 使用 jQuery 時:
inArray()簡單,但由於程式庫開銷較慢。
Summary
本節比較了主要陣列搜尋方法,並根據情境說明其推薦使用方式。 Key Points:
- 簡單搜尋使用
indexOf()或includes()。 - 條件搜尋使用
find()或findIndex()。 - 舊版 jQuery 環境使用
inArray()。
根據您的環境和使用情境選擇適當方法,有助於建立高效且易於維護的程式碼。 
5. 實際範例和應用情境
本節說明如何在實務情境中應用 JavaScript 與 jQuery 陣列搜尋方法。透過實作範例,您將加深程式碼的理解。
5-1. 表單輸入驗證
情境:
驗證使用者的輸入是否存在於預先定義的清單中。
解決方案:
使用 includes() 進行簡單的存在性檢查。
程式碼範例:
const validColors = ['red', 'green', 'blue'];
const userInput = 'green';
if (validColors.includes(userInput)) {
console.log('Valid color.');
} else {
console.log('Invalid color.');
}
5-2. 搜尋與擷取使用者資料
情境:
在物件陣列中搜尋符合特定條件的使用者資料。
解決方案:
使用 find() 或 findIndex()。
程式碼範例:
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 },
];
const result = users.find(user => user.age >= 30);
console.log(result); // Output: { id: 2, name: 'Bob', age: 30 }
const index = users.findIndex(user => user.age >= 30);
console.log(index); // Output: 1
5-3. 錯誤處理範例
情境:
當搜尋目標未找到時實作錯誤處理。
解決方案:
使用 indexOf() 或 findIndex()。
程式碼範例:
const products = ['apple', 'banana', 'orange'];
const index = products.indexOf('grape');
if (index === -1) {
console.log('Product not found.');
} else {
console.log(`Product found at index ${index}.`);
}
5-4. 篩選陣列資料
情境:
僅提取符合特定條件的資料。
解決方案:
使用 filter()。
程式碼範例:
const scores = [45, 72, 88, 53, 94];
const highScores = scores.filter(score => score >= 70);
console.log(highScores); // Output: [72, 88, 94]
5-5. jQuery 搜尋範例
情境:
在舊有系統中使用 inArray() 檢查資料是否存在。
解決方案:
使用 jQuery 的 inArray()。
程式碼範例:
const fruits = ['apple', 'banana', 'orange'];
if ($.inArray('banana', fruits) !== -1) {
console.log('Banana exists in the list.');
} else {
console.log('Banana is not in the list.');
}
小結
本節介紹了基於實務情境的實用使用範例。
重點:
includes()簡單且適用於輸入驗證。find()與findIndex()在條件式與物件搜尋上功能強大。indexOf()在錯誤處理上相當彈性。filter()可有效提取多筆符合條件的項目。inArray()在舊版 jQuery 環境中很有幫助。
6. 常見問題集 (FAQ)
本節針對 JavaScript 與 jQuery 陣列搜尋的常見問題提供解答。
問題 1:indexOf() 與 includes() 有何差異?
回答:
兩個方法皆用於在陣列中搜尋元素,但其回傳值與使用方式不同:
indexOf():回傳指定值的索引;若未找到則回傳-1。includes():回傳布林值(true或false),表示陣列中是否存在該值。
範例:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.includes('banana')); // Output: true
問題 2:find() 與 filter() 有何不同?
回答:
兩個方法皆會回傳符合條件的元素,但功能上有所差異:
find():回傳第一個符合條件的元素。filter():回傳所有符合條件的元素,形成新陣列。
範例:
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.find(num => num > 25)); // Output: 30
console.log(numbers.filter(num => num > 25)); // Output: [30, 40, 50]
問題 3:如何在物件陣列中搜尋特定的鍵值對?
回答:
使用帶條件的 find() 或 findIndex()。
範例:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
];
const user = users.find(user => user.name === 'Bob');
console.log(user); // Output: { id: 2, name: 'Bob' }
問題 4:我還應該使用 jQuery 的 inArray() 嗎?
答案:
jQuery 的 inArray() 在舊有環境中仍然有用,但現代 JavaScript 已提供更好的原生方法。
建議:
- 新專案:使用原生方法,如
indexOf()或includes()。 - 既有的 jQuery 系統:使用
inArray()以維持一致性。
問題 5:如何優化陣列搜尋的效能?
答案:
針對大型資料集或頻繁的搜尋操作,請留意以下要點:
1. 選擇快速的方法:
indexOf()與includes()是最適合簡單搜尋的最快方法。
2. 使用快取:
- 快取搜尋結果以避免重複計算。
3. 優化資料結構:
- 對於大型資料集,使用物件、
Map或Set以提升查找效率。
範例:
const dataSet = new Set([10, 20, 30, 40]);
console.log(dataSet.has(20)); // Output: true
小結
本節說明了 JavaScript 與 jQuery 中常見的陣列搜尋問題。
重點:
- 了解各方法的差異並適當選擇。
find()在物件陣列的條件搜尋中相當有用。- 現代開發優先使用原生方法;jQuery 主要用於舊有系統。
- 透過正確的資料結構選擇來優化效能。

7. 小結與後續步驟
本文詳細說明了 JavaScript 與 jQuery 的陣列搜尋方法。讓我們回顧重點,並討論如何持續學習與應用這些概念。
7-1. 重點摘要
1. 基本陣列搜尋方法
indexOf():搜尋元素的索引。includes():回傳布林值,表示值是否存在。find()/findIndex():搜尋符合條件的第一個元素或其索引。
2. jQuery 的 inArray() 方法
- 在舊有或以 jQuery 為基礎的系統中仍具實用性。
- 現代開發建議使用原生 JavaScript 方法。
3. 實務範例與應用情境
- 輸入驗證、使用者資料抽取、錯誤處理與過濾等,都可透過這些方法簡化。
4. 常見問答
- 說明差異、使用情境與效能考量。
7-2. 如何選擇適合的方法
選擇方法取決於使用目的。請參考下方速查表:
| Use Case | Recommended Method |
|---|---|
| Simple value search | indexOf() or includes() |
| Conditional search | find() or findIndex() |
| Multiple matching elements | filter() |
| Legacy jQuery environment | inArray() |
| High-performance lookup (large data) | Set or Map |
7-3. 後續步驟
1. 開始一個小型專案
- 建立簡易的 Web App,實作本章學到的方法。
範例:待辦清單、商品庫存管理、過濾工具。
2. 深入學習進階 JavaScript
- ES6+ 功能:展開運算子、解構賦值、箭頭函式。
- 非同步程式設計:學習
Promise、async/await以處理資料取得。
3. 探索前端框架
- 如 React 或 Vue.js 等框架,常使用陣列操作來渲染 UI。
4. 推薦資源
- MDN Web Docs: JavaScript 陣列
- W3Schools: JavaScript 陣列方法
- JSFiddle / CodePen:適合測試與分享程式碼片段。
7-4. 最後的想法
透過本指南,你已學會 JavaScript 與 jQuery 中陣列搜尋的基礎與進階應用。
給讀者的建議:
- 多寫多測,將所學實作於程式碼中。
- 持續探索新的 JavaScript 功能與技巧。
- 依據具體需求選擇最適合的方法。
結論
這就結束了《JavaScript 與 jQuery 陣列搜尋完整指南》。
持續學習並擴展您的程式設計技能,以打造更強大且更高效的應用程式。



