标签:ie8 uniq 浏览器 unique script llb length prot number
<script type="text/javascript"> //indexOf”是ECMAScript5方法,IE8以下不支持,需多写兼容低版本浏览器代码。 Array.prototype.indexOf=Array.prototype.indexOf|| function(item){ for(var i=0;i<this.length;i++) { if(this[i]===item) { return i; } } return -1; } var obj={ name:‘312‘ } function newobj(){ } var a=[0,0,new String(1), new Number(1),obj,obj,new newobj(),new newobj()]; Array.prototype.forEach = Array.prototype.forEach || function(callback, thisArg) { if (!callback || typeof callback !== ‘function‘) return; for (var i = 0, j = this.length; i < j; i++) { callback.call(thisArg, this[i], i, this); } } function removeDuplicatedItem1(arr) { var ret=[]; for(var i=0;i<arr.length;i++) { if(ret.indexOf(arr[i])===-1) { ret.push(arr[i]); } } return ret; } // 0 1 1 [object object] [object object ][object object] function removeDuplicatedItem2(arr) { var ret=[]; arr.forEach(function(e,i,arr){ if(arr.indexOf(e)===i) ret.push(e); }); return ret; } //// 0 1 1 [object object] [object object ][object object] function removeDuplicatedItem3(ar) { var ret = [], end; ar.sort(); end = ar[0]; ret.push(ar[0]); for (var i = 1; i < ar.length; i++) { if (ar[i] !== end) { ret.push(ar[i]); end = ar[i]; } } return ret; }// 0 1 1 [object object] [object object ][object object] //上述都做了两次循环 因此需要优化 function removeDuplicatedItem4(arr)//unique([ new String(1), new Number(1) ]) 无法判断 { var tem={}; var ret=[]; for(var i=0;i<arr.length;i++) { var item=arr[i]; var key=typeof(item)+item; //因为对象只能存放字符串,所以要区分 1 ‘1‘ if(!tem[key]) { tem[key]=1; ret.push(item); } } return ret; } //0 1 [object object] </script>
标签:ie8 uniq 浏览器 unique script llb length prot number
原文地址:http://www.cnblogs.com/herozhou/p/6910409.html