javascript數組去重的三種方法

var aList = [1,2,3,4,4,3,2,1,2,3,4,5,6,5,5,3,3,4,2,1];

方法一:

    <script>
        var aList = [1, 2, 3, 4, 4, 3, 2, 1, 2, 3, 4, 5, 6, 5, 5, 3, 3, 4, 2, 1];
        /*  1.建立一個空的列表
         2.判斷當前的列表的數據是否在空的列表中存在,如果存在,那不添加,如果不存在添加*/
        var list_new = new Array();

        for (var i = 0; i < aList.length; i++) {
            /*判斷是否在空的列表中存在*/
            if (list_new.indexOf(aList[i]) == -1) {
                /*不存在*/
                /*添加數據*/
                list_new.push(aList[i])
            }
        }

        console.log(list_new);


    </script>

方法二:

 <script>
        var aList = [1, 2, 3, 4, 4, 3, 2, 1, 2, 3, 4, 5, 6, 5, 5, 3, 3, 4, 2, 1];
        /*  1.建立一個空的列表
         2.判斷當前的列表的數據是否在空的列表中存在,如果存在,那不添加,如果不存在添加*/
        var list_new = new Array();
//
        for (var i = 0; i < aList.length; i++) {
            /*判斷是否在空的列表中存在*/
            if (list_new.indexOf(aList[i]) +1) {
               /*說明非0 就是有數據就是true*/
                console.log('數據重複了');
            }else {
                /*說明沒有,可以添加數據*/
                list_new.push(aList[i])
            }
        }

        console.log(list_new);

        //        前端非0true,0是false
//        if(0) {
//            console.log('0');
//        }else {
//            console.log('非0');
//        }


    </script>

方法三:

<script>
        var aList = [1, 2, 3, 4, 4, 3, 2, 1, 2, 3, 4, 5, 6, 5, 5, 3, 3, 4, 2, 1];
        //        當前的位置與我們的indexof的位置是一致,那麼說明是第一個元素

        var list_new = []

        for (var i = 0; i < aList.length; i++) {
            //當前的位置與我們的indexof的位置是一致,那麼說明是第一個元素
            if (aList.indexOf(aList[i]) == i) {
                list_new.push(aList[i])
            }
        }

        console.log(list_new);
    </script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章