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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM