js 对象的深拷贝

function deepCopy(obj) {
    var result = Array.isArray(obj) ? [] : {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] === 'object') {
                result[key] = deepCopy(obj[key]); // 递归复制
            } else {
                result[key] = obj[key];
            }
        }
    }
    return result;
}
var obj = {
    name:111
}
var obj2 = deepCopy(obj)
obj2.name = 333
console.log(obj2)

 

posted @ 2019-05-24 17:18  史海莹  阅读(163)  评论(0编辑  收藏  举报