萬盛學電腦網

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

JavaScript 數組擴展 contains/includes 方法:從 Polyfill 到現代標準

現代標準:Array.prototype.includes

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(IE 支持)

// 符合規範的完整 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]

TypeScript 類型擴展

// 全局擴展(如需添加自定義方法)
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];
};

性能提示

  • 小數組(<50):includes、indexOf 差異可忽略
  • 大數組頻繁查找:轉為 Set 或 Map,O(1) 查找
  • Set.from(array).has(value) 比 array.includes(value) 快 10-100 倍
copyright © 萬盛學電腦網 all rights reserved