其他分享
首页 > 其他分享> > 浅拷贝与深拷贝

浅拷贝与深拷贝

作者:互联网

浅拷贝

let stu = {
    name:'xiaoming',
    age:10,
    bestFriend:{
        name:'zhangsan',
        age:25
    }
}


function copyObject(obj){
    let newObj = {};
    for (let i in obj){
        newObj[i] = obj[i]
    }
    return newObj
}
let  newStu = copyObject(stu)

console.log(stu)
console.log(newStu)
console.log(stu === newStu)//false

深拷贝

两种方式

  1. 递归

    let stu = {
        name:'xiaoming',
        age:10,
        bestFriend:{
            name:'zhangsan',
            age:25
        }
    }
    
    function copyObjects(obj){
        let newObj = {};
        for (let i in obj){
            if (obj[i] instanceof Object){
                newObj[i] = copyObjects(obj[i]);
            }else{
                newObj[i] = obj[i]
            }
        }
        return newObj
    }
    let  newStu2 = copyObjects(stu)
    stu.bestFriend.name = 'lisi'
    console.log(stu)
    console.log(newStu2)
    console.log(stu === newStu2)
    
  2. 转JSON

    let stu = {
        name:'xiaoming',
        age:10,
        bestFriend:{
            name:'zhangsan',
            age:25
        }
    }
    
    function copyObjects(obj){
    
        let newStr = JSON.stringify(obj);
        let newObj = JSON.parse(newStr);
        return newObj
    }
    let  newStu2 = copyObjects(stu)
    stu.bestFriend.name = 'lisi'
    console.log(stu)
    console.log(newStu2)
    console.log(stu === newStu2)
    

标签:obj,log,newObj,stu,let,console,拷贝
来源: https://www.cnblogs.com/warm-px/p/16031350.html