javascript中如何去掉数组中的重复项

<!DOCTYPE html>

<html lang="en">

<head>

         <meta charset="UTF-8">

         <title>Document</title>

         <script type="text/javascript">

                   //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="xushouwei";

                   // obj.age=30;

                   //把数组变成对象

                   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));

         </script>

</head>

<body>

</body>

</html>

posted @ 2017-04-12 20:08  徐守威  阅读(633)  评论(0编辑  收藏  举报