JavaScript一些向下的兼容操作

Array

indexOf ( IE11不支持)

兼容性地址 IE不支持

if (typeof Array.prototype.indexOf !== 'function') {
  Array.prototype.indexOf = function (elt /*, from */) {  /* eslint-disable-line */
         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;
     };
 }

includes ( IE11不支持)

兼容性地址 IE不支持

if (typeof Array.prototype.includes !== 'function') {
    Array.prototype.includes = function (filter) {  /* eslint-disable-line */
        return this.indexOf(filter) > -1;
    };
}

forEach (>IE9)且IE9的嚴格模式不支持

兼容性地址 (>IE9)且IE9的嚴格模式不支持

if (typeof Array.prototype.forEach !== 'function') {
    /** forEach高階函數 */
    Array.prototype.forEach = function (fn) {  /* eslint-disable-line */
        for (var index = 0; index < this.length; index++) {
            var element = this[index];
            fn(element,index,this);
        }
    };
}

reduce ( IE11不支持)

兼容性地址 ( IE11不支持)

if (typeof Array.prototype.reduce !== 'function') {
    /** reduce高階函數 作用累加 累減
     *  
     */
    Array.prototype.reduce = function (fn,prev) {  /* eslint-disable-line */
        // var that = ;
        this.forEach(function (value,index,arr) {
            prev =  fn(prev,value,index,arr);
        });
        return prev;
    };
}

map ( IE11不支持)

兼容性地址 ( IE11不支持)

if (typeof Array.prototype.map !== 'function') {
    /** map 生成新的數組*/
    Array.prototype.map = function (fn) {  /* eslint-disable-line */
        var reuslt = [];
        this.forEach(function (value,index,arr) {
            reuslt.push( fn(value,index,arr));
        });
        return reuslt;
    };
}

remove

if (typeof Array.prototype.remove !== 'function') {
    Array.prototype.remove = function (item) {  /* eslint-disable-line */
        var ind = this.indexOf(item);
        return ind > -1 ? this.splice(ind, 1) : false;
    };
}

includes

if (typeof String.prototype.includes !== 'function') {
    String.prototype.includes = function (filter) {  /* eslint-disable-line */
        return this.indexOf(filter) > -1;
    };
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章