1 Array.prototype.unique1 = function () {
2 var n = []; //一个新的临时数组
3 for (var i = 0; i < this.length; i++) //遍历当前数组
4 {
5 //如果当前数组的第i已经保存进了临时数组,那么跳过,
6 //否则把当前项push到临时数组里面
7 if (n.indexOf(this[i]) == -1) n.push(this[i]);
8 }
9 return n;
10 };
11
12
13 Array.prototype.unique2 = function()
14 {
15 var n = {},r=[]; //n为hash表,r为临时数组
16 for(var i = 0; i < this.length; i++) //遍历当前数组
17 {
18 if (!n[this[i]]) //如果hash表中没有当前项
19 {
20 n[this[i]] = true; //存入hash表
21 r.push(this[i]); //把当前数组的当前项push到临时数组里面
22 }
23 }
24 return r;
25 };
26
27
28 Array.prototype.unique3 = function()
29 {
30 var n = [this[0]]; //结果数组
31 for(var i = 1; i < this.length; i++) //从第二项开始遍历
32 {
33 //如果当前数组的第i项在当前数组中第一次出现的位置不是i,
34 //那么表示第i项是重复的,忽略掉。否则存入结果数组
35 if (this.indexOf(this[i]) == i) n.push(this[i]);
36 }
37 return n;
38 };
39
40
41 Array.prototype.unique4 = function()
42 {
43 this.sort();
44 var re=[this[0]];
45 for(var i = 1; i < this.length; i++)
46 {
47 if( this[i] !== re[re.length-1])
48 {
49 re.push(this[i]);
50 }
51 }
52 return re;
53 };
54
55
56 var arr = [1,2,2,2,3,3,4,5];
57 console.log(arr.unique1()); // [1, 2, 3, 4, 5]
58 console.log(arr.unique2()); // [1, 2, 3, 4, 5]
59 console.log(arr.unique3()); // [1, 2, 3, 4, 5]
60 console.log(arr.unique4()); // [1, 2, 3, 4, 5]