【转】JS深拷贝

作者:青笠
链接:http://www.zhihu.com/question/23031215/answer/31944721
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

google一下JS深拷贝,知乎这个问题竟然排在第四
=============================================================
var cloneObj = function(obj){
    var str, newobj = obj.constructor === Array ? [] : {};
    if(typeof obj !== 'object'){
        return;
    } else if(window.JSON){
        str = JSON.stringify(obj), //系列化对象
        newobj = JSON.parse(str); //还原
    } else {
        for(var i in obj){
            newobj[i] = typeof obj[i] === 'object' ? 
            cloneObj(obj[i]) : obj[i]; 
        }
    }
    return newobj;
};

这个函数可以深拷贝 对象和数组

猜你喜欢

转载自7708801314520.iteye.com/blog/2319383