1. 程式人生 > >編寫一個數組去重的方法

編寫一個數組去重的方法

<script>
    var arr = [1,2,"2","4",5,2,1];

    var newArr = removeRepetition(arr);
    console.log(newArr);

    function removeRepetition(arr){
        var newArr = [];
        //typeof (arr) == "string"?newArr = "":newArr = [];
        if (newArr.length == 0) {
            newArr.push(arr[0]);
        }
        if (newArr.length != 0) {
            for (var i in arr) {
                if (newArr.indexOf(arr[i]) == -1) {
                    newArr.push(arr[i]);
                }
            }
        }
        if(typeof arr == "object"){
            return newArr;
        }
        if(typeof arr == "string"){
            var arrStr = "";
            for(var i=0;i<newArr.length;i++){
                arrStr += newArr[i];
            }
            return arrStr;
        }
    }

</script>