20181005 js数组去重的三种方法

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>数组去重</title>
    </head>
    <body>
        <script type="text/javascript">
            //注意有一个元素是空的
            var test1 = [0,0,1,1,2,'sss',2,,3,'abc',3,4,4,'sss','apple',5,5,6,7,8,9,function a(){}];
            //第一种方法是遍历新数组newArr里有没有包含arr里的i项,如果没有则向newArr里添加arr[i]项,如果有则跳过
            //需考虑indexOf()的兼容性问题
            function arrayUnique1(arr){
                var newArr = [];
                for(var i =0; i < arr.length; i++){
                    if(newArr.indexOf(arr[i]) == -1){
                        newArr.push(arr[i]);
                    }
                }
                return newArr;
            }
            console.log(arrayUnique1(test1)); //[0, 1, 2, "sss", undefined, 3, "abc", 4, "apple", 5, 6, 7, 8, 9, function]
             //第二种方法
            var test2 = [0,0,1,1,2,'sss',2,,3,'abc',3,4,4,'sss','apple',5,5,6,7,8,9,function a(){}];
            //先将数组进行排序,重复元素会在相邻位置
            //拿原数组第i个和新数组的最后一个进行比较,如果不同,则将该元素存入新数组中
            //该方法由于使用sort()方法,所以会改变数组顺序
            function arrayUnique2(arr){
                arr.sort();
                var newArr = [arr[0]];
                for(var i = 1; i < arr.length; i++){
                    if(arr[i] !== newArr[newArr.length-1] ){
                        newArr.push(arr[i]);
                    }
                }
                return newArr;
            }
            console.log(arrayUnique2(test2));//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "abc", "apple", function, "sss", undefined]
            // 第三种方法
            var test3 = [0,0,1,1,2,'sss',2,,3,'abc',3,4,4,'sss','apple',5,5,6,7,8,9,function a(){}];
            //不太熟悉hash表,大概意思如下:
            //遍历原数组,每次从原数组取出一个元素,然后到新对象中去访问这个属性,如果不能访问到值,则把它存放到新数组中,同时把这个元素作为一个属性,并赋值为true,存入到新建立的对象中。如果能访问到值,则说明重复;
             
            //访问对象的属性有两种方式   obj['attr']  或者   obj.attr;
            //当知道具体属性名时可以用obj.attr,如arr.length;当不确定属性名时,就要用obj['attr'];
            //这两种方法区别上不大,都有对应的使用场景。点表示法一般作为静态对象使用时来存取属性。而数组表示法在动态存取属性时就非常有用。
            function arrayUnique3(arr){
                var newArr = [],
                    hash = {};
                for(var i = 0; i < arr.length; i++){
                    if(!hash[arr[i]]){
                        hash[arr[i]] = true;
                        newArr.push(arr[i]);
                    }
                }
                return newArr;
            }
            console.log(arrayUnique3(test3));//[0, 1, 2, "sss", undefined, 3, "abc", 4, "apple", 5, 6, 7, 8, 9, function]
        </script>
    </body>
</html>
posted @ 2018-10-05 19:32  街角的守护  阅读(175)  评论(0编辑  收藏  举报