萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 判斷陣列包含指定元素:從 prototype 擴充到現代 includes/find

判斷陣列是否包含某值是高頻操作。本文回顧早期 Array.prototype.contains 擴充寫法,對比現代 includes、indexOf、find、some 標準方法,並討論效能與語意差異。

早期擴充寫法(不推薦污染原型)

Array.prototype.contains = function(needle) {
  for (var i in this) { // for...in 會遍歷可列舉屬性,包含原型鏈,極不推薦
    if (this[i] === needle) return true;
  }
  return false;
};

// 使用
var arr = [1,2,3];
arr.contains(2); // true

嚴重缺陷:

  • for...in 遍歷索引而非值,且包含繼承屬性,極易出錯。
  • 污染 Array.prototype 影響所有陣列,第三方庫衝突風險高。
  • 無法區分 NaN(NaN !== NaN)。

現代標準方法(ES6+)

Array.prototype.includes(searchElement, fromIndex) —— 最語意化

[1, 2, 3].includes(2);           // true
[1, 2, 3].includes(4);           // false
[NaN].includes(NaN);             // true  (關鍵優勢:正確處理 NaN)
['a', 'b', 'c'].includes('a', 1); // false(fromIndex=1 從索引 1 開始找)

瀏覽器支援:Chrome 47+、Firefox 43+、Edge 14+、Safari 9+。IE 需 Polyfill。

Array.prototype.indexOf(searchElement, fromIndex) —— 經典替代

[1,2,3].indexOf(2) !== -1; // true
[NaN].indexOf(NaN);        // -1 (無法找到 NaN)

Array.prototype.find(predicate) —— 複雜判斷條件

const users = [{id:1, name:'Alice'}, {id:2, name:'Bob'}];
users.find(u => u.id === 2);           // {id:2, name:'Bob'}
users.find(u => u.name.startsWith('A')) // {id:1, name:'Alice'}

Array.prototype.some(predicate) —— 只需布林結果

users.some(u => u.id === 99); // false
users.some(u => u.name.length > 3); // true

效能對比(百萬級陣列)

| 方法 | 時間複雜度 | 實測 100萬數字陣列 | 備註 | |------|------------|-------------------|------| | includes | O(n) | ~2ms | 原生優化、語意最清晰 | | indexOf | O(n) | ~2ms | 同樣優化,但 NaN 問題 | | find | O(n) | ~3ms | 回呼函數微小開銷 | | some | O(n) | ~3ms | 同 find | | Set.has | O(1) | ~0.1ms | **頻繁查詢時先轉 Set** |

最佳實踐建議

  • 單次查詢、基本型別:arr.includes(val) 碼最少、語意最明確。
  • 需支援 IE:引入 core-js Polyfill 或用 indexOf !== -1。
  • 查詢物件/複雜條件:arr.find(item => item.id === targetId)。
  • 高頻查詢同一陣列:const set = new Set(arr); set.has(val),建構 Set 成本 O(n),查詢 O(1),查詢超過 ~10 次即回本。
  • 嚴禁擴充原型:污染全域、破壞封裝、阻礙 Tree Shaking。

TypeScript 類型提示

function contains<T>(arr: readonly T[], value: T): boolean {
  return arr.includes(value);
}

// 使用
const ids = [1,2,3] as const;
contains(ids, 2); // true
contains(ids, '2'); // 型別錯誤:Argument of type 'string' is not assignable to parameter of type 'number'

善用現代標準 API,代碼更簡潔、更安全、更易維護。

copyright © 萬盛學電腦網 all rights reserved