1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2 <html>
3 <head>
4 <title> New Document
</title>
5 <meta name="Generator" content="EditPlus">
6 <meta name="Author" content="">
7 <meta name="Keywords" content="">
8 <meta name="Description" content="">
9 </head>
10
11 <body>
12 <script type="text/javascript">
13 <!--1.最容易想到的数组去重算法,
14 Array.prototype.clearRepetitionA = function(){
15 var result = [];
16 var isRepetition; //标记是否重复
17 for(var i=0;i<this.length;i++){
18 isRepetition = false;
19 for(var j=0;j<result.length;j++){
20 if(this[i]===result[j]){
21 isRepetition = true;
22 break;
23 }
24 }
25 if(!isRepetition){
26 result.push(this[i]);
27 }
28 }
29 return result;
30 }
31 -->
32
33 <!--2.利用数组的indexOf方法检索元素
34 Array.prototype.clearRepetitionB = function(){
35 var result = [];
36 for(var i=0;i<this.length;i++){
37 if(result.indexOf(this[i])==-1){
38 result.push(this[i]);
39 }
40 }
41 return result;
42 }
43 -->
44
45 <!--3.查找源数组的元素是否是第一次出现,是则插入
46 Array.prototype.clearRepetitionC = function(){
47 var result = [this[0]];
48 for(var i=1;i<this.length;i++){
49 if(this.indexOf(this[i])==i){
50 result.push(this[i]);
51 }
52 }
53 return result;
54 }
55 -->
56
57 <!--4.
58 Array.prototype.clearRepetitionD = function(){
59 var result = [];
60 var obj = {}; //JSON js中一种简单定义对象的方式
61 var key,type;
62 for(var i=0;i<this.length;i++){
63 key = this[i];
64 type = typeof key;//返回 undefined/boolean/string/number/object/function
65 if(!obj[key]){ //obj[key]是找对象obj属性key对应的属性值,没找到返回undefined
66 obj[key] = [type];
67 result.push(key);
68 }else if(obj[key].indexOf(type)){
69 obj[key].push(type);
70 result.push(key);
71 }
72 }
73 return result;
74 }
75
76 对象obj的属性----源数组的值
77 对象obj的属性值--数组[源数组的值的类型]
78 "源数组的值":[源数组的值的类型,类型,类型]
79
80 -->
81
82 <!--5.细想一下,非常有意思,灰常牛
83 Array.prototype.clearRepetitionE = function(){
84 var result = [];
85 for(var i=0;i<this.length;i++){
86 for(var j=i+1;j<this.length;j++){
87 if(this[i]===this[j]){
88 j=++i; //先计算
89 }
90 }
91 result.push(this[i]);
92 }
93 return result;
94 }
95 -->
96
97 <!--6.先排序再去重
98 Array.prototype.clearRepetitionF = function(){
99 this.sort();
100 var result = [this[0]];
101 for(var i=1;i<this.length;i++){
102 if(this[i]!==result[result.length-1]){
103 result.push(this[i]);
104 }
105 }
106 return result;
107 }
108 -->
109
110 </script>
111 </body>
112 </html>
转载于:https://www.cnblogs.com/xiao-fan-fan-2015/p/4770977.html
相关资源:JavaScript数组去重算法实例小结
转载请注明原文地址: https://win8.8miu.com/read-1485943.html