码迷,mamicode.com
首页 > Web开发 > 详细

JS浅拷贝和深拷贝

时间:2020-05-03 10:49:47      阅读:70      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!