1.删除后面重复的:
function ov1(arr) {
//var a1=((new Date).getTime())
for (var i = 0; i < arr.length; i++) for (var j = i + 1; j < arr.length; j++) if (arr[i] === arr[j]) {
arr.splice(j, 1);
j--;
}
//console.info((new Date).getTime()-a1)
return arr.sort(function(a, b) {
return a - b
});
}
2.这个是常规的方法,比较好理解,如果相同则跳出循环
function ov2(a) {
//var a1=((new Date).getTime())
var b = [],
n = a.length,
i,
j;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) if (a[i] === a[j]) {
j = false;
break;
}
if (j) b.push(a[i]);
}
//console.info((new Date).getTime()-a1)
return b.sort(function(a, b) {
return a - b
});
}
3.这个我花了好长时间明白的,这里j循环虽然继续了,但是i值已经改变了。就等于是一个新的i循环:·
//code from http://caibaojian.com/js-delrepeat.html#0-tsina-1-33614-397232819ff9a47a7b7e80a40613cfe1
function ov3(a) {
//var a1=((new Date).getTime())
var b = [],
n = a.length,
i,
j;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) if (a[i] === a[j]) j = ++i b.push(a[i]);
}
//console.info((new Date).getTime()-a1)
return b.sort(function(a, b) {
return a - b
});
}
4.保证新数组中的都是唯一的
function ov4(ar) {
//var a1=((new Date).getTime())
var m = [],
f;
for (var i = 0; i < ar.length; i++) {
f = true;
for (var j = 0; j < m.length; j++) if (ar[i] === m[j]) {
f = false;
break;
};
if (f) m.push(ar[i])
}
//console.info((new Date).getTime()-a1)
return m.sort(function(a, b) {
return a - b
});
}
5.用对象属性
function ov5(ar) {
// var a1=(new Date).getTime()
var m, n = [],
o = {};
for (var i = 0; (m = ar[i]) !== undefined; i++) if (!o[m]) {
n.push(m);
o[m] = true;
}
// console.info((new Date).getTime()-a1)
return n.sort(function(a, b) {
return a - b
});;
}
来源: 前端开发博客