转载自:https://blog.csdn.net/chengxuyuan20100425/article/details/8497277
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
Array.prototype.unique1 = function () {
var n = [];//一个新的临时数组
for (var i = 0; i < this.length; i++) {//遍历当前数组
//如果当前数组的第i已经保存进了临时数组,那么跳过,
//否则把当前项push到临时数组里面
if (n.indexOf(this[i]) == -1) n.push(this[i]);
}
return n;
}
/* 注意:1, '1'等不同类型的值可能对应到同一个下标而被去重,但实际应该保留。 把 hash 表的值改为一个数组,里面保存出现过的类型就行了。 */
Array.prototype.unique2 = function () {
//n为hash表,r为临时数组
var n = {}, r = [], len = this.length, val, type;
for (var i = 0; i < this.length; i++) {
val = this[i];
type = typeof val;
if (!n[val]) {//如果hash表中没有当前项
n[val] = type;//存入hash表
r.push(val);//把当前数组的当前项push到临时数组里面
} else if (n[val].indexOf(type) < 0) {
n[val] = type;
r.push(val);
}
}
console.log("n: ", n);
return r;
}
Array.prototype.unique3 = function () {
var n = [this[0]];//结果数组
for (var i = 1; i < this.length; i++) {//从第二项开始遍历
if (this.indexOf(this[i]) == i) {
//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
//那么表示第i项是重复的,忽略掉。否则存入结果数组
n.push(this[i]);
}
}
return n;
}
/* 这个方法的思路是先把数组排序,然后比较相邻的两个值。 排序的时候用的JS原生的sort方法,JS引擎内部应该是用的快速排序吧。 最终测试的结果是此方法运行时间平均是第二种方法的三倍左右,不过比第一种和第三种方法快了不少。 */
Array.prototype.unique4 = function () {
this.sort();
var n = [this[0]];
for (var i = 1; i < this.length; i++) {
if (this[i] !== n[n.length - 1]) {
n.push(this[i]);
}
}
return n;
}
var arr = [1, 1, 2, 3, 1, 666, "11", "11", undefined, undefined, null, null, "", "", { 1: 2 }, { 1: 2 }];
console.log("unique1", arr.unique1());
console.log("unique2", arr.unique2());
console.log("unique3", arr.unique3());
console.log("unique4", arr.unique4());
console.log();
</script>
</body>
</html>