今天看了 oneroom的 【javascript数字数组去重复项 】觉得挺有意思的。顺便把我以前在看的对比一下。也算是做个备份。
第一种:也是最笨的吧。
view source print ? 01 Array.prototype.unique1 = function () { 02 var r = new Array(); 03 label: for ( var i = 0, n = this .length; i < n; i++) { 04 for ( var x = 0, y = r.length; x < y; x++) { 05 if (r[x] == this [i]) { 06 continue label; 07 } 08 } 09 r[r.length] = this [i]; 10 } 11 return r; 12 }
第二种:这个正则天书一样。
view source print ? 1 Array.prototype.unique2 = function () { 2 return this .sort().join( ",," ).replace(/(,|^)([^,]+)(,,/2)+(,|$)/g, "$1$2$4" ).replace(/,,+/g, "," ).replace(/,$/, "" ).split( "," ); 3 }
第三种:使用对象的【hasOwnProperty】方法
view source print ? 01 Array.prototype.unique3 = function () { 02 var temp = {}, len = this .length; 03 for ( var i=0; i < len; i++) { 04 var tmp = this [i]; 05 if (!temp.hasOwnProperty(tmp)) { 06 temp[ this [i]] = "my god" ; 07 } 08 } 09 10 len = 0; 11 var tempArr=[]; 12 for ( var i in temp) { 13 tempArr[len++] = i; 14 } 15 return tempArr; 16 }
第四种:先排序,前项比后项。这个方法挺简单的,但也实用。
view source print ? 01 Array.prototype.unique4 = function () { 02 var temp = new Array(); 03 this .sort(); 04 for (i = 0; i < this .length; i++) { 05 if ( this [i] == this [i+1]) { 06 continue ; 07 } 08 temp[temp.length]= this [i]; 09 } 10 return temp; 11 12 }
下面是以前经常用的,效率也很好。有点想hash表的感觉。
view source print ? 01 Array.prototype.unique5 = function () { 02 var res = [], hash = {}; 03 for ( var i=0, elem; (elem = this [i]) != null ; i++) { 04 if (!hash[elem]) 05 { 06 res.push(elem); 07 hash[elem] = true ; 08 } 09 } 10 return res; 11 }
还要谢谢oneroom 他给demo里面的时间计算函数很好用。以前我都不知道测试这些效率呢。
稍后附上他的demo和Watch文件。
摘自:http://www.cnblogs.com/serf/archive/2010/12/29/1921132.html