數組去重問題

面試,常常趕上這個問題,因此,寫篇文章總結下吧:javascript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>數組去重方法總結</title>
</head>
<body>
<script type="text/javascript">
var array1=[1,1,1,2,3,4,4,4,11,12,11,13,12,6,6,6,11,12,13];
var array2=[];
// 效率較低;新建一個數組,存貯未重複元素,添加控制器,若是元素不重複,則添加進新數組
Array.prototype.unique1=function(){
    var res=[this[0]];
    console.log(res)
    for(var i=0;i<this.length;i++){
        var repeat=false;
        for(var j=0;j<res.length;j++){
            if(this[i]==res[j]){
                repeat=true;
                break;
            }
        }if(!repeat){
            res.push(this[i]);
        }
    }
    return res;
};
//console.log(array1.unique1());
//改變了數組順序
Array.prototype.unique2=function(){
    this.sort();//想一想【1,1,11,12,11,】
    var res=[this[0]];
    for(i=0;i<this.length;i++){
        if(this[i]!==res[res.length-1]){
            res.push(this[i]);
        }
    }
    return res;
};
//console.log(array1.unique2());
//第三種主要是利用控制器,對每一個數組的數值轉換爲腳,實際上,json返回的就是不重複元素的第一個序號
Array.prototype.unique3=function(){
    var res=[];
    var json={};
    for(i=0;i<this.length;i++){
        if(!json[this[i]]){
            res.push(this[i]);
            json[this[i]]=1;
        }
    }
    console.log(json);
    return res;
};
//console.log(array1.unique3());
Array.prototype.indexOf=function(e){
    for(i=0;i<this.length;i++){
        j=this[i];
        if (j==e) {
            return i;
            break;
        }
    }
    return -1;
};
//console.log(array1.indexOf(4))
Array.prototype.unique4=function(){
    var res=[];
    for(i=0;i<this.length;i++){
        if (res.indexOf(this[i])==-1) {
            res.push(this[i]);
        }
    }
    return res;
};
console.log(array1.unique4());//這種方法有待改正,瀏覽器會卡死。這只是一種理論上的方法
</script>
</body>
</html>
相關文章
相關標籤/搜索