ES2016 (ES7) 已標準化,無需手動擴展:
[1, 2, 3].includes(2); // true
[1, 2, 3].includes('2'); // false(嚴格相等)
[NaN].includes(NaN); // true(修復 indexOf 缺陷)
['a', 'b', 'c'].includes('a', 1); // false,fromIndex=1 從索引 1 開始找
// 符合規範的完整 Polyfill
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
if (this == null) throw new TypeError('"this" is null or not defined');
const o = Object(this);
const len = o.length >>> 0;
if (len === 0) return false;
const n = fromIndex | 0;
let k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
while (k < len) {
if (sameValueZero(o[k], searchElement)) return true;
k++;
}
return false;
},
configurable: true,
writable: true
});
}
| 誤區 | 正確做法 |
|---|---|
修改原型鏈 Array.prototype.contains = ... | 使用 Object.defineProperty 設置 enumerable: false,避免污染 for...in |
用 indexOf !== -1 判斷 | 無法檢測 NaN,語義不明確 |
| 對象數組用 includes 判斷 | 引用比較,需用 some(item => item.id === targetId) |
| 稀疏數組漏檢 | includes 會訪問空位,indexOf 會跳過 |
// 查找索引
[1,2,3].indexOf(2); // 1
[1,2,3].lastIndexOf(2); // 1
[1,2,3].findIndex(x => x > 1); // 1
// 查找元素
[1,2,3].find(x => x > 1); // 2
// 斷言所有/任一
[2,4,6].every(x => x % 2 === 0); // true
[1,2,3].some(x => x > 2); // true
// ES2023 新增(可變更副本)
const arr = [3,1,2];
arr.toSorted(); // [1,2,3] 原數組不變
arr.toReversed(); // [2,1,3]
arr.toSpliced(1,1); // [3,2]
arr.with(0, 9); // [9,1,2]
// 全局擴展(如需添加自定義方法)
interface Array<T> {
// 避免與標準庫衝突,建議前綴
firstOrDefault(predicate?: (item: T) => boolean): T | undefined;
lastOrDefault(predicate?: (item: T) => boolean): T | undefined;
}
Array.prototype.firstOrDefault = function(predicate) {
if (predicate) return this.find(predicate);
return this[0];
};
includes、indexOf 差異可忽略Set 或 Map,O(1) 查找Set.from(array).has(value) 比 array.includes(value) 快 10-100 倍