我自仰头向天笑,笑完我就去睡觉,哈哈哈哈……

js去除数组重复

这个算法确实经典,做个笔记。

 1 <script>
 2 
 3 Array.prototype.unique = function() {
 4     for( var a={}, i=0; i<this.length; i++ ) {
 5         if( typeof( a[ this[i] ] ) === "undefined" ) {
 6             a[ this[i] ] = 1;  // a.1 = 1, a.2 = 1, a.3 = 1
 7         }
 8     }
 9     this.length=0;
10     for(i in a) {
11         this[this.length] = i;  // arr[ 0 ] = 1, arr[ 1 ] = 2;
12     }
13     return this;
14 }
15 
16 var a = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,11];
17 
18 document.write(a);  // 1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,11
19 
20 document.write(a.unique());  // 1,2,3,4,5,6,7,8,11 
21 
22 </script>
posted @ 2012-09-22 18:19  轻轻的烟雾  阅读(181)  评论(0编辑  收藏  举报