首页 > 技术文章 > 关于 ie8不兼容的一些方法

xianhuiwang 2017-12-01 16:47 原文

ie8 不兼容的方法 

 

$(function(){
    //添加数组IndexOf方法
    if (!Array.prototype.indexOf){
      Array.prototype.indexOf = function(elt /*, from*/){
        var len = this.length >>> 0;
    
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
          from += len;
    
        for (; from < len; from++){
          if (from in this && this[from] === elt)
            return from;
        }
        return -1;
      };
    }
    
    //getOwnPropertyNames keys 方法
    if(!Object.getOwnPropertyNames || !Object.keys){
        Object.keys = Object.getOwnPropertyNames = function(temp){
            var A = [];
            for(var key in temp){
                A.push(key);
            }
            return A;
        }
    }
    
    //forEach 方法
    if ( !Array.prototype.forEach ) {  
      Array.prototype.forEach = function forEach( callback, thisArg ) {  
        var T, k;  
        if ( this == null ) {  
          throw new TypeError( "this is null or not defined" );  
        }  
        var O = Object(this);  
        var len = O.length >>> 0;   
        if ( typeof callback !== "function" ) {  
          throw new TypeError( callback + " is not a function" );  
        }  
        if ( arguments.length > 1 ) {  
          T = thisArg;  
        }  
        k = 0;  
        while( k < len ) {  
          var kValue;  
          if ( k in O ) {  
            kValue = O[ k ];  
            callback.call( T, kValue, k, O );  
          }  
          k++;  
        }  
      };  
    }  
    
    //filter 方法
    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisArg */)
      {
        "use strict";
    
        if (this === void 0 || this === null)
          throw new TypeError();
    
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function")
          throw new TypeError();
    
        var res = [];
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++)
        {
          if (i in t)
          {
            var val = t[i];
    
            // NOTE: Technically this should Object.defineProperty at
            //       the next index, as push can be affected by
            //       properties on Object.prototype and Array.prototype.
            //       But that method's new, and collisions should be
            //       rare, so use the more-compatible alternative.
            if (fun.call(thisArg, val, i, t))
              res.push(val);
          }
        }
    
        return res;
      };
    }
})

 

推荐阅读