JS浅拷贝和深拷贝

Posted 西瓜的夏天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS浅拷贝和深拷贝相关的知识,希望对你有一定的参考价值。

/**
 * 浅拷贝
 * @type {{address: {name: string}, sex: number, name: string}}
 */
let person1 = {
    sname: ‘tommy‘
}

let person2 = person1;
person2.sname = ‘hello,tommy!‘
console.log(person2.sname) // hello,tommy!
console.log(person1.sname)  //hello,tommy!

/**
 *  深拷贝
 * @type {{address: {name: string}, sex: number, name: string}}
 */
let person = {
    name: ‘jack‘,
    sex: 6,
    address: {
        name: ‘陕西西安‘
    }
}

var person3 = deepCopy(person);
person3.address.name = ‘新疆乌鲁木齐‘
console.log(person3)  // { name: ‘jack‘, sex: 6, address: { name: ‘新疆乌鲁木齐‘ } }
console.log(person)   // { name: ‘jack‘, sex: 6, address: { name: ‘陕西西安‘ } }

function deepCopy(obj = {}) {
    let result
    if (typeof obj != "object" || obj == null) {
        return obj
    }

    if (obj instanceof Array) {
        result = []
    } else {
        result = {}
    }

    for (let key in obj) {
        result[key] = deepCopy(obj[key])
    }

    return result
}

 

以上是关于JS浅拷贝和深拷贝的主要内容,如果未能解决你的问题,请参考以下文章

JS-[浅拷贝和深拷贝]

js的浅拷贝和深拷贝

js浅拷贝(地址引用)和深拷贝(克隆)

js实现浅拷贝和深拷贝

JS 原生方法原理探究如何实现浅拷贝和深拷贝?

js运用递归实现浅拷和深拷贝