例1
常用见的去除重复数组,但不能排序
代码如下 |
复制代码 |
Array.prototype.unique1 = function () {
var r = new Array();
label:for(var i = 0, n = this.length; i < n; i++) {
for(var x = 0, y = r.length; x < y; x++) {
if(r[x] == this[i]) {
continue label;
}
}
r[r.length] = this[i];
}
return r;
}
|
一个比较高级的但是我没看懂
代码如下 |
复制代码 |
Array.prototype.unique2 = function () {
return this.sort().join(",,").replace(/(,|^)([^,]+)(,,2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
}
|
例2
去除重复数组并排序
代码如下 |
复制代码 |
Array.prototype.unique = function(){
var a = {};
var len = this.length;
for(var i=0; i<len; i++) {
if(typeof a[this[i]] == "undefined") a[this[i]] = 1;
}
this.length = 0;
for(var i in a) {
this[this.length] = i;
}
return this;
}
|
|