判斷陣列是否包含某值是高頻操作。本文回顧早期 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)。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
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) 碼最少、語意最明確。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 次即回本。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,代碼更簡潔、更安全、更易維護。