首頁 > web前端 > js教程 > 主體

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

WBOY
發布: 2016-05-16 18:12:57
原創
1126 人瀏覽過
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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板