JS浅拷贝和深拷贝

2021-03-13 05:31

阅读:351

标签:lse   var   OLE   string   copy   color   ons   style   hello   

/**
 * 浅拷贝
 * @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浅拷贝和深拷贝

标签:lse   var   OLE   string   copy   color   ons   style   hello   

原文地址:https://www.cnblogs.com/yangxuming/p/12820808.html


评论


亲,登录后才可以留言!