日期:2014-05-16 浏览次数:20566 次
利用javascript编写一个去除数组重复项的方法,时间复杂度O(n),大家看看有没有什么漏洞或者写出自己更好的方法
<html>
?<head>
??<script type="text/javascript">
???function distinct(arr){
????var rs = new Array();
????for(var i=0;i<arr.length;i++){
?????var s = ","+rs.join(",")+",";
?????if(!s.match(","+arr[i]+",")){
??????rs.push(arr[i]);
?????}?
????}
????return rs;
???}
???var r = new Array(1,2,212,2);
???alert(distinct(r).toString());
??</script>
?</head>
?<body>
?</body>
</html>
var array=[1,1,2,2,3,3]; var newArry=[]; for(var x in array){ newArry[array[x]]=""; } for(var y in newArry){ alert(y); }
var s = ["a","b","a","c"]; var arr = [], map = {}, n, i; for(i=0; i<s.length; i++){ n = s[i]; if(!map.hasOwnProperty(n)){ map[n] = true; arr.push(n); } } console.log(arr);
Array.prototype.say="haha"; var array=[new Object(),"1,2#<%^&*()+}[]{",2,2,3,3,4,4,6,6,5,5]; var newArry=[]; for(var x in array){ newArry[array[x]]=""; } for(var y in newArry){ alert(y+" "+typeof y); }
var array=["a","b","c","a"]; for(var i=0;i<array.length;i++){ for(var j=i+1;j<array.length;j++){ if(array[j]==array[i]) array.splice(j,1) } } alert(array);
var array=[2.3,2.3,"a","b","b",true,true,false,1,0,undefined,null]; for(var i=0;i<array.length;i++){ for(var j=i+1;j<array.length;j++){ if(array[j]===array[i]) array.splice(j,1) } } alert(array);
var array=[2.3,2.3,"a","b","b",true,true,true,false,1,0,undefined,null]; for(var i=0;i<array.length;i++){ for(var j=i+1;j<array.length;j++){ if(array[j]===array[i]) { array.splice(j,1); j--; } } } alert(array);
var array=[2.3,2.3,"a","b","b",true,true,true,false,1,0,undefined,null]; for(var i=0;i<array.length;i++){ for(var j=i+1;j<array.lengt