本方法修改自 CSDN 的 meizz(梅花雪),主要提升了一点点性能,95%的代码都未修改,请梅老师见谅
<
script
>
Array.prototype.uniq = function () {
var temp = {}, len = this .length;
for ( var i = 0 ; i < len; i ++ ) {
if ( typeof temp[ this [i]] == " undefined " ) {
temp[ this [i]] = 1 ;
}
}
this .length = 0 ;
len = 0 ;
for ( var i in temp) {
this [len ++ ] = i;
}
return this ;
}
var a = [ " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1
, " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1
, " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1
, " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 ];
var b = [ 2 , 3 , 5 , 7 ];
// --------------------------时间测试开始-------------------------
start = new Date().getTime();
var c = a.concat(a).concat(b).concat(a).concat(b).concat(a)
.concat(b).concat(a).concat(b).concat(a).concat(b)
.concat(a).concat(b).concat(b).concat(a).concat(b).uniq();
document.write(c + " 长度 " + c.length);
end = new Date().getTime();
document.write( " 耗时: " + (end - start) + " ms " )
// --------------------------时间测试结束--------------------------
// IE结果:sss,aaa,4,2,3,1,5,7 长度 8 耗时:15ms
// FF结果:sss,aaa,4,2,3,1,5,7 长度 8 耗时:2ms
</ script >
Array.prototype.uniq = function () {
var temp = {}, len = this .length;
for ( var i = 0 ; i < len; i ++ ) {
if ( typeof temp[ this [i]] == " undefined " ) {
temp[ this [i]] = 1 ;
}
}
this .length = 0 ;
len = 0 ;
for ( var i in temp) {
this [len ++ ] = i;
}
return this ;
}
var a = [ " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1
, " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1
, " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1
, " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 , " sss " , " aaa " , " sss " , 4 , 2 , 3 , 1 , 1 ];
var b = [ 2 , 3 , 5 , 7 ];
// --------------------------时间测试开始-------------------------
start = new Date().getTime();
var c = a.concat(a).concat(b).concat(a).concat(b).concat(a)
.concat(b).concat(a).concat(b).concat(a).concat(b)
.concat(a).concat(b).concat(b).concat(a).concat(b).uniq();
document.write(c + " 长度 " + c.length);
end = new Date().getTime();
document.write( " 耗时: " + (end - start) + " ms " )
// --------------------------时间测试结束--------------------------
// IE结果:sss,aaa,4,2,3,1,5,7 长度 8 耗时:15ms
// FF结果:sss,aaa,4,2,3,1,5,7 长度 8 耗时:2ms
</ script >