Rumah > hujung hadapan web > tutorial js > javascript数字数组去重复项的实现代码_javascript技巧

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

WBOY
Lepaskan: 2016-05-16 18:12:57
asal
1156 orang telah melayarinya
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>
Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan