首页 > 其他 > 详细

手写浅拷贝

时间:2020-12-26 20:26:52      阅读:43      评论:0      收藏:0      [点我收藏+]

记录贴

 

// 手写浅拷贝
    let arr = [1,2,3,4,5]
    let obj = {
        name:1
    }
    function My(){
        this.age = 0
        
        My.prototype.nes = function(){
            console.log("哈哈")
        }
    }
    
    let Obj = new My()
    // assing
    let news = Object.assign({},obj)
    news.name = 132
    console.log(news,obj)
    //Array.concat;Array.slice;[...Array]
    
    
    console.log(shallowCopy(Obj))
    
    function type(data){
        let    datas = Object.prototype.toString.call(data).slice(8,-1)
        return datas
    }
    
    function shallowCopy(target){
        let result = type(target) == "Object"?{}:[]
        for(let e in target){
            if(target.hasOwnProperty(e)){
                if(typeof target[e] === "object"){
                    if(target[e] === null){
                        result[e] = null
                    }else{
                        shallowCopy(target[e])
                    }
                }else{
                    result[e] = target[e]
                }
            }
        }
        return result
    }

 

手写浅拷贝

原文:https://www.cnblogs.com/styleFeng/p/14193548.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!