JS -- 去重

        var array = [1, 1, "2", '1']

1.Set()

        var con = new Set(array)
        console.log(con);        // Set(3) {1, "2", "1"}

 

2.indexOf()

        function unique(array) {
            var res = [];
            for (var i = 0, len = array.length; i < len; i++) {
                var current = array[i];
                if (res.indexOf(current) === -1) {
                    res.push(current)
                }
            }
            return res;
        }

        console.log(unique(array));        // (3) [1, "2", "1"]

 

3.filter


        function uniquef(array) {
            var resp = [];
            var res = array.filter(function (item, index, array) {
                return array.indexOf(item) === index;
            })
            return res;
        }
        console.log(uniquef(array));        // (3) [1, "2", "1"]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章