JavaScript首页投稿(暂停使用,暂停投稿)让前端飞

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

2017-06-27  本文已影响284人  亚当斯密

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

<!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>

结束!

上一篇 下一篇

猜你喜欢

热点阅读