首页 > web前端 > js教程 > 正文

javascript数字数组去重复项的实现代码_javascript技巧

WBOY
发布: 2016-05-16 18:12:57
原创
1123 人浏览过
test.htm
复制代码 代码如下:





array-remove-repeate







<script> <br><br>if(!console) <BR>{ <BR>var console={}; <BR>console.log=function(str){alert(str);} <BR>} <br><br>Array.prototype.unique1 = function () { <BR>var r = new Array(); <BR>label:for(var i = 0, n = this.length; i < n; i++) { <BR>for(var x = 0, y = r.length; x < y; x++) { <BR>if(r[x] == this[i]) { <BR>continue label; <BR>} <BR>} <BR>r[r.length] = this[i]; <BR>} <BR>return r; <BR>} <br><br>Array.prototype.unique2 = function () { <BR>return this.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(","); <BR>} <br><br>Array.prototype.unique3 = function() { <BR>var temp = {}, len = this.length; <BR>for(var i=0; i < len; i++) { <BR>var tmp = this[i]; <BR>if(!temp.hasOwnProperty(tmp)) { <BR>temp[this[i]] = "my god"; <BR>} <BR>} <br><br>len = 0; <BR>var tempArr=[]; <BR>for(var i in temp) { <BR>tempArr[len++] = i; <BR>} <BR>return tempArr; <BR>} <BR>Array.prototype.unique4 = function () { <BR>var temp = new Array(); <BR>this.sort(); <BR>for(i = 0; i < this.length; i++) { <BR>if( this[i] == this[i+1]) { <BR>continue; <BR>} <BR>temp[temp.length]=this[i]; <BR>} <BR>return temp; <br><br>} <br><br><BR>var test=(function() <BR>{ <BR>var arr2=[]; <BR>for(var i=0;i<2000;i++) <BR>{ <BR>var t=i; <BR>t=parseInt(Math.random()*2000)+1; <BR>arr2[i]=(t.toString()); <br><br><BR>} <BR>//arr2=["zhoujian","zhou","zhou"]; <BR>return function(){ <BR>return arr2; <BR>//return [1,2,3,3]; <BR>}; <br><br><BR>})(); <BR>window.onload=function(){ <br><br><BR>// <BR>Watch.start("Cost times1:"); <BR>var arr= test(); <BR>console.log(arr.length ); <br><br>arr=arr.unique1(); <BR>console.log(arr.length); <br><br>Watch.stop(); <BR>// <BR>Watch.start("Cost times2:"); <BR>arr= test(); <BR>console.log(arr.length); <br><br><BR>arr=arr.unique2(); <br><br>console.log(arr.length); <br><br>Watch.stop(); <BR>// <BR>Watch.start("Cost times3:"); <BR>arr= test(); <BR>console.log(arr.length ); <br><br>arr=arr.unique3();//</script>
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板