深拷贝浅拷贝

//浅拷贝
var obj = {
    name: 'jack',
    age: 18
}
const newObj = obj
console.log('obj', obj)
console.log('newObj', newObj)
//深拷贝
var oldObj = {
    name: 'jack',
    age: 18
}

function deepClone(obj) {
    let result
    
    if (typeOf obj !== 'object') {
        return obj
    }
    
    if (obj instanceof Array) {
        result = []
    } else {
        result = {}
    }
    
    for (let i in obj) {
        result[i] = deepClone(obj[i])
    }
    return result
}


const newObj = deepClone(oldObj)
newObj.name = 'tom'
console.log('oldObj', oldObj)
console.log('newObj', newObj)
//利用 JSON.parse() 和 JSON.stringify()实现深拷贝
var obj = {
    name: '小明',
    grilFriend: { name: '小红' }
}

function deepClone(obj) {
    let _obj = JSON.stringify(obj);
    let data = JSON.parse(_obj);
    return data
}
var newObj = deepClone(obj);
newObj.grilFriend.name = '小花'
console.log(obj, newObj)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容