深拷贝代码(包含对null,数组,及对象的判断)

        var duyy={
            name:"duyy",
            age:20,
            scroe:null,
            firend:["wangxs","sunff"],
            add:{prov:"北京",city:"北京",area:"昌平"}
        }
        function copy(obj){
            var newobj={}
            //判断是否为null
            if(obj===null){
                return null
            }
            for(var key in obj){
            //判断数组
                if({}.toString.call(obj)==="[object Array]"){
                    var newarr=[];
                    newarr=obj.slice()
                    return newarr
                }
                if(typeof obj[key]!=="object"){
                    newobj[key]=obj[key]
                }else{
                    newobj[key]=copy(obj[key])
                }
            }
            return newobj
        }
        var duyy1=copy(duyy);
        duyy.scroe=20;
        console.log(duyy1)
        console.log(duyy)

你可能感兴趣的:(js类)