萬盛學電腦網

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

為 IE 補全缺失的 String/Array 原型方法(startsWith、contains、indexOf)

老版本 IE (6-8) 缺少 ES5/ES6 標準方法,通過原型擴展可實現兼容,但需注意**不要污染原型鏈**與**避免覆蓋原生實現**。

String.prototype.startsWith (ES6)

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchStr, position) {
    position = position || 0;
    return this.slice(position, position + searchStr.length) === searchStr;
  };
}

Array.prototype.indexOf (ES5)

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var len = this.length >>> 0;
    fromIndex = +fromIndex || 0;
    if (fromIndex < 0) fromIndex = Math.max(len + fromIndex, 0);
    for (; fromIndex < len; fromIndex++) {
      if (fromIndex in this && this[fromIndex] === searchElement) return fromIndex;
    }
    return -1;
  };
}

Array.prototype.contains (非標準,常見工具方法)

if (!Array.prototype.contains) {
  Array.prototype.contains = function(item) {
    return this.indexOf(item) !== -1;
  };
}

最佳實踐原則

  1. 優先檢測是否已存在(if (!Array.prototype.xxx)),避免覆蓋原生高效實現。
  2. 使用 Object.defineProperty 設置 enumerable: false,防止 for...in 遍歷污染。
    Object.defineProperty(Array.prototype, 'contains', {
      value: function(item) { return this.indexOf(item) !== -1; },
      writable: true, configurable: true, enumerable: false
    });
  3. 現代專案**直接引入 core-js 或 babel-polyfill**,統一由構建工具按目標環境注入 polyfill,手動擴展僅作舊專案維護。

補充:String.prototype.trim (ES5)

if (!String.prototype.trim) {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  };
}
copyright © 萬盛學電腦網 all rights reserved