Heim > Web-Frontend > js-Tutorial > javascript数字数组去重复项的实现代码_javascript技巧

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

WBOY
Freigeben: 2016-05-16 18:12:57
Original
1154 Leute haben es durchsucht
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>
Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage