封裝數組去重的方法(三種)

額.......................
第一種:

<!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日,你來到我們的家 自此 我們成為了彼此的唯一 三更半夜清理大小便 ...
    在天邊在人間閱讀 255評論 0 1
  • 作為《舌尖上的中國》的總導演,陳曉卿顯然是這個節目的核心人物,能夠如此恰到好處的把握全國億萬人民的味蕾,讓大家都看...
    陳妮弗勞倫斯閱讀 583評論 0 2
  • 第138天~ 5.20屬于你和她的節日~ 一個人的我~ 幸福甜蜜的你們~ 祝你節日快樂,而不是你們~ 好嘛?! 想...
    法斗SEVEN閱讀 173評論 0 0