重写默认方法兼容ie, 比如filter,keys等
Posted 晓菲
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重写默认方法兼容ie, 比如filter,keys等相关的知识,希望对你有一定的参考价值。
重写 Object.keys, Array.prototype.map, Array.prototype.filter, Array.prototype.reduce, 使其适合ie
1. keys
Object.myKeys = function (params) { var ary = []; if (Object.keys) { ary = this.keys(params); } else { for(var key in params ) if(hasOwn.call(params,key)){ ary.push(key) ; } var DONT_ENUM = "propertyIsEnumerable,isPrototypeOf,hasOwnProperty,toLocaleString,toString,valueOf,constructor".split(","), hasOwn = ({}).hasOwnProperty; for (var i in { toString: 1 }){ DONT_ENUM = false; } if(DONT_ENUM && params){ for(var i = 0 ;key = DONT_ENUM[i++]; ){ if(hasOwn.call(params,key)){ ary.push(key); } } } } return ary; }
2.使ie 支持map
Array.prototype.myMap = function (fn, context) { context = context || window; var ary = []; if (Array.prototype.map) { ary = this.map(fn, context); } else { for (var i = 0; i < this.length; i++) { ary[i] = fn.apply(context, [this[i], i, this]); } } return ary; }
3. filter
Array.prototype.myFilter = function (fn) { var ary = []; if (Array.prototype.filter) { ary = this.filter(fn); } else { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fn !== "function") throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; if (fn.call(thisArg, val, i, t)) ary.push(val); } } } return ary; }
4. refuce
Array.prototype.myReduce = function (callback, opt_initialValue) { var value = ‘‘; if (Array.prototype.reduce) { value = this.reduce(callback, opt_initialValue); } else { if (this === void 0 || this === null) { throw new TypeError(); } var index, length = this.length >>> 0, isValueSet = false; if (1 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (index = 0; length > index; ++index) { if (this.hasOwnProperty(index)) { if (isValueSet) { value = callback(value, this[index], index, this); } else { value = this[index]; isValueSet = true; } } } if (!isValueSet) { value = ‘‘; //throw new TypeError(‘Reduce of empty array with no initial value‘); } } return value; }
以上是关于重写默认方法兼容ie, 比如filter,keys等的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript数组方法的兼容性写法 汇总:indexOf()forEach()map()filter()some()every()