深克隆

作者: Vivian_06e6 | 来源:发表于2018-08-30 23:11 被阅读0次

    方法1:

    function deepClone(obj){
        if(Array.isAray(obj)){
            var _obj = [];
            for(var key in obj){
                _obj.push(deepClone(obj[key])) ;
            }
            return _obj;
        }else if(typeof obj == "object"){
            var _obj={};
            for(var key in obj){
                _obj[key] = deepClone(obj[key])
            }
            return _obj;
        }else{
            return obj
        }
    }
    
    
    

    方法2:

    //this is javascript
    function deepClone(src,target){
        var target = target||{};
        var toStr = Object.prototype.toString;
        for (var attr in src){
            if((typeof src[attr])=="object"&&(typeof src[attr])!==null){
                target[attr] = toStr.call(src[attr])=="[object object]"?{}:[];
                deepClone(src[attr],target[attr])
            }else if ((typeof src[attr])==null){
                target[attr] = null;
            } if ((typeof src[attr])==undefined){
                target[attr] = undefined;
            }else{
                target[attr] = src[attr];
            }
        }
        return target;
    }
    
    image

    相关文章

      网友评论

          本文标题:深克隆

          本文链接:https://www.haomeiwen.com/subject/agdjwftx.html