封装数组去重的方法(三种)

额.......................
第一种:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        Array.prototype.count = function(){
            for(var i = 0; i < this.length-1; i++){
                for(var j = i+1; j < this.length; j++){
                    if(this[i] == this[j]){
                        this.splice(j,1);
                        i--;
                    }
                    // 去重后排序
                    // if(this[i] > this[j]){
                    //  [this[i],this[j]] = [this[j],this[i]];
                    }
                }
            }
            console.log(this)
        }
        var newArr = [1,2,9,66,99,3,3,3,3,3,3,3,3,33,4,4,5,6,-111,0,9,-3,-2,0];
        newArr.count();
    </script>
</body>
</html>

第二种:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数组去重</title>
</head>
<body>
    <script type="text/javascript">
        Array.prototype.count = function(){
            for (var i = 0; i < this.length-1; i++) {
                for(var j = i+1; j < this.length; j++){
                    if(this[j] > this[i]){
                        var temp = this[j];
                        this[j] = this[j+1];
                        this[j+1] = temp;
                    }
                }
            };
        }
        var newArr = [1,3,2,4,5,6,3,33,44,22,3]; 
    </script>
</body>
</html>

第三种:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        function count(arr){
            var newArr = [];
            for(var i = 0;i < arr.length; i++){
                if(newArr.indexOf(arr[i])==-1){
                    newArr.push(arr[i]);
                }
            }
            //本地排序(去重后)
            newArr.sort(function(a,b){
                return a-b;
            });
            return newArr;
            }
        var newAr1 = [1,2,2,2,2,3,3,3,4,4,5,5,65,6,6,6];
        console.log(count(newAr1))
    </script>
</body>
</html>

结束!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 7月15日,你来到我们的家 自此 我们成为了彼此的唯一 三更半夜清理大小便 ...
    在天边在人间阅读 257评论 0 1
  • 作为《舌尖上的中国》的总导演,陈晓卿显然是这个节目的核心人物,能够如此恰到好处的把握全国亿万人民的味蕾,让大家都看...
    陈妮弗劳伦斯阅读 589评论 0 2
  • 第138天~ 5.20属于你和她的节日~ 一个人的我~ 幸福甜蜜的你们~ 祝你节日快乐,而不是你们~ 好嘛?! 想...
    法斗SEVEN阅读 174评论 0 0