1.浅拷贝 => 在引用数据类型当中,我们只拷贝一层: let studentInfo = { name:"张三", age:18, gender:"男", address:{ addressInfo1:"江西", addressInfo2:"深圳" }, hobby:["唱","跳","rap","篮球","music"] } let personInfo = {} // 将studentInfo赋值一份给personInfo => 这个不叫做拷贝,只是将studentInfo里面的地址复制一份,给personInfo// personInfo = studentInfo 浅拷贝: for(let key in studentInfo){ personInfo[key] = studentInfo[key] } 修改张三的姓名 studentInfo.name = "李四" studentInfo.address.addressInfo1 = "湖南" console.log(personInfo,studentInfo); 之前所学过的 ... 扩展运算符 Object.assign() //将后面的studentInfo浅拷贝一份给personInfo// Object.assign(personInfo,studentInfo) 扩展运算符: personInfo = {...studentInfo} studentInfo.name = "王五" studentInfo.address.addressInfo1 = "四川" console.log(personInfo,studentInfo); 2.深拷贝 => 需要递归: function deepCopy(newData,oldData){ // 遍历老的对象的时候 //如果是基本数据类型 => 直接拷贝 //如果是引用数据类型 => // 数组 => 创建一个新的数组 => 对数组里面的内容进行拷贝 // 对象 => 创建一个新的对象 => 对对象里面的内容进行拷贝 for(let key in oldData){ console.log(Object.prototype.toString.call(oldData[key])); if(Object.prototype.toString.call(oldData[key]) == '[object Object]'){ //创建一个新的数组 newData[key] = {} //对复杂(引用)数据类型进行深层次的拷贝 deepCopy(newData[key],oldData[key]) }else if(Object.prototype.toString.call(oldData[key]) == '[object Array]'){ newData[key] = [] deepCopy(newData[key],oldData[key]) }else{ newData[key] = oldData[key] } } } deepCopy(personInfo,studentInfo); studentInfo.name = "王五" studentInfo.address.addressInfo1 = "四川" console.log(personInfo,studentInfo);