猿问

JavaScript数组值去重,但是返回的类型和原类型不一样了 帮帮忙

<script  type="text/javascript" charset="utf-8" async defer>

var arr = [2,1,2,10,2,3,4,1,85,321,3,4,65,10,24];

function uniq(newarr){

    function toObject(arr) {

        var obj = { };

         for(var i=0 ;i<arr.length ;i++){

            obj[ arr[ i ] ]=true;

            }

        return obj ;

    }

    function keys(obj){

        var arr = [ ] ;

            for(var attr in obj){

                if(obj.hasOwnProperty(attr)){

                    arr.push(parseInt(attr));

                }

            }

        return arr;

    }

return keys(toObject(newarr));

}


console.log(uniq(arr));


qq_想到就做到_0
浏览 1424回答 1
1回答

李晓健

没发现你那个哪里不一样呀,你可以试一下其他的方法,比喻先排序,然后把相邻相同的都去掉<script>     var arr = [2,1,2,10,2,3,4,1,85,321,3,4,65,10,24];     var newArray = arr.sort(function(a,b){return a-b;});     var arr2=[];     arr2.push(newArray[0]);     for(var i=0;i<newArray.length-1;i++){         if(newArray[i] !== newArray[i+1]){             arr2.push(newArray[i+1])         }     }     console.log(arr2); </script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答