Javascript作业—数组去重(要求:原型链上添加函数)

数组去重(要求:原型链上添加函数)

<script>
//数组去重,要求:在原型链上添加函数

//存储不重复的--仅循环一次
if(!Array.prototype.unique1){
    Array.prototype.unique1=function(){
        var item ,
            hash={},
            len=this.length,
            result=[];
        for(var i = 0 ; i < len ; i++){
            item = this[i];
            if(!hash[item+Object.prototype.toString.call(item)]){ //1 和 '1'的处理
                result.push(item);
                hash[item+Object.prototype.toString.call(item)]=true;
            }
        }
        return result;
    }
}
 
//去除重复的--循环次数太多,不好
Array.prototype.unique2=function (){
    for(var i=0;i <=this.length;i++){
        for(var j=i+1;j<=this.length;j++)
        {
            if(arr[i]===arr[j]){arr.splice(j,1);j--;} //去除重复
        }
    }
    return arr;
}


var arr=[1,'1',2,3,3,4,5,4,4];

</script>
原文地址:https://www.cnblogs.com/dinghanhua/p/9708139.html