日期:2014-05-16  浏览次数:20340 次

javascript缺重代码

如果数组中只有字符串的话:
Js代码1
1.var s = ["a","b","a","c"];??
2.var arr = [], map = {}, n, i;??
3.for(i=0; i<s.length; i++){??
4.??? n = s[i];??
5.??? if(!map.hasOwnProperty(n)){??
6.??????? map[n] = true;??
7.??????? arr.push(n);??
8.??? }??
9.}??
10.console.log(arr);?
Js代码2
1.var array=["a","b","c","a"];??
2.for(var i=0;i<array.length;i++){??
3.??? for(var j=i+1;j<array.length;j++){??
4.?????? if(array[j]==array[i]) {
?????????? array.splice(j,1)
?????????? j--;
???????? }
5.??? }??
6.}??
7.alert(array);?
Js代码3:
1.var array=[1,1,2,2,3,3];??
2.var newArry=[];??
3.for(var x in array){??
4. newArry[array[x]]="";??
5.}??
6.for(var y in newArry){??
7.alert(y);??
8.}
for in循环比较危险,它会枚举原型链上的属性:
1.Array.prototype.say="haha";??
2.var array=[new Object(),"1,2#<%^&*()+}[]{",2,2,3,3,4,4,6,6,5,5];??
3.var newArry=[];??
4.for(var x in array){??
5.??????? newArry[array[x]]="";??
6.}??
7.for(var y in newArry){??
8.??? alert(y+" "+typeof y);??
9.}?

适合任何类型缺重:
1.var array=[2.3,2.3,"a","b","b",true,true,true,false,1,0,undefined,null];??
2.for(var i=0;i<array.length;i++){??
3.??? for(var j=i+1;j<array.length;j++){??
4.?????? if(array[j]===array[i]) {??
5.?????????? array.splice(j,1);??
6.?????????? j--;??
7.???????? }??
8.?????????
9.??? }??
10.}??
11.alert(array);?