数组的去重

<!DOCTYPE html>

<html lang="en">

<head>

         <meta charset="UTF-8">

         <title>Document</title>

         <script type="text/javascript">

       //方法1:

                   //js对象特性:在js对象中key是永远不会重复的

                   /*

                            1.把数组转成一个js对象

                            2.把数组中的值变成js对象中的key

                            3.把这个对象再次还原成数组

                   */

                   var arr=[2,1,2,10,2,3,5,10,13];

                   // var obj=new Object();

                   // obj.name="zhaoyuxiang";

                   // obj.age=23;

                   //把数组变成对象

                   function toObject(arr)

                   {

                            var obj={};

                            for(var i=0;i<arr.length;i++)

                            {

                                     obj[arr[i]]=true;

                            }

                            return obj;

                   }

                   //把对象变成数组

                   function keys(obj)

                   {

                            var arr=[];

                            for(var attr in obj)

                            {

                                     if(obj.hasOwnProperty(attr))

                                     {

                                               arr.push(attr);

                                     }

                            }

                            return arr;

                   }

                   //综合的方法用于去掉数组中的重复项

                   function uniq(newarr)

                   {

                            return keys(toObject(newarr));

                   }

                   console.log(uniq(arr));

 

 

 

      //方法2:

      var arr=[2,6,57,7,2,8,5,9,8,4,7];
      var arr1=[];
      var k=0;
      for(var i=0;i<arr.length;i++){
        if(qc(arr1,arr[i])){
          arr1[k]=arr[i];
          k++;
        }
      }


      function qc(arr,val){
        for(var j=0;j<arr.length;j++){
          if(arr[j]==val){
            return false;
          }
        }
        return true;
      }

      console.log(arr1);

         </script>

</head>

<body>

</body>

</html>

posted on 2017-05-09 10:44  skylark_one  阅读(134)  评论(0编辑  收藏  举报

导航