使用对象键值对方式(推荐)
var ary = [12, 2, 1, 2, 232, 12, 3321]
Array.prototype.Unique = function Unique() {
var obj = {}
for (var i = 0; i < this.length; i++) {
var cur = this[i]
if (obj[cur] == cur) {
this[i] = this[this.length - 1];
this.length--;
i--;
continue
}
obj[cur] = cur
}
obj = null
return this
}
ary.Unique()
console.log(ary)
Array.prototype.Unique = function () {
var obj = {};
for (var i = 0; i < this.length; i++) {
var item = this[i]
if (typeof obj[item] !== 'undefined') {
this[i] = this[this.length - 1];
this.length--;
i--;
continue
}
obj[item] = true;
}
obj = null;
return this
}
var arr = [12, 12, 23, 45, 56, 787, 23, 56]
arr.Unique()
console.log(arr)
2,双循环去重(不推荐)
Array.prototype.Unique = function () {
for (var i = 0; i < this.length; i++) {
var item = this[i];
for (var j = i + 1; j < this.length; j++) {
if (item == this[j]) {
this[i] = this[this.length - 1]
this.length--;
i--;
break
}
}
}
return this
}
var arr = [12, 12, 23, 34, 45, 56, 56]
arr.Unique()
console.log(arr)
3,indexOf 去重(不兼容ie6-8)
Array.prototype.Unique = function () {
for (var i = 0; i < this.length; i++) {
var item = this[i],
ary = this.slice(i + 1);
if (ary.indexOf(item) > -1) {
this[i] = this[this.length - 1];
this.length--;
i--;
}
}
return this
}
var arr = [12, 12, 23, 323, 23]
arr.Unique()
console.log(arr)
4,排序后去重
Array.prototype.Unique = function () {
var _this = this.sort(function (a, b) {
return a - b
});
var ary = [];
for (var i = 0; i < _this.length; i++) {
var item = _this[i],
next = _this[i + 1];
if (item !== next) {
ary.push(item)
}
}
return ary
}
var ary = [12, 23, 12, 23, 23, 12]
ary.Unique()
console.log( ary.Unique())