拷贝
拷贝: 复制对象
浅拷贝: 只复制一层对象
深拷贝: 复制得到不一样的对象
实现拷贝
浅拷贝
let obj = {
name: 'jack',
age: 18,
fun: {
swiming: '游泳',
},
}
// {...obj} [...arr]
// let newObj = { ...obj } // 浅拷贝,如果属性值是对象不能拷贝
// let newObj = Object.assign(obj)
newObj.name = 'rose'
newObj.fun.swiming = '打游戏'
console.log('newObj :',newObj.name, ' oldObj :',obj.name);
console.log('newObj fun :',newObj.fun.swiming, ' oldObj fun :',obj.fun.swiming);
console.dir(newObj);
console.dir(obj);
深拷贝
JSON对象:1.JSON.stringify(obj) //obj --> 字符串
注意:只能是Object形式对象
2.JSON.parse(str) //字符串 --> obj
注意:字符串必须是JSON格式
function test1() {
let objStr = JSON.stringify(obj)
console.log(obj)
console.log(objStr, typeof objStr)
let str = '{"num":1001,"score":98}'
let obj1 = JSON.parse(str)
console.log(obj1)
console.log(obj1.num)
}
let obj = {
name: 'jack',
age: 18,
fun: {
swiming: '游泳',
},
say:function(){
console.log('说话');
},
score:undefined
}
// 利用JSON实现深拷贝
// let str = JSON.stringify(obj) //obj->str
// let newObj = JSON.parse(str) // str->obj
let newObj = JSON.parse(JSON.stringify(obj))
newObj.name = 'rose'
newObj.age = 20
newObj.fun.swiming = '玩游戏'
console.dir(newObj)
console.dir(obj)
递归实现深拷贝
function cloneObj(obj){
let newObj = Array.isArray(obj)? []:{} // 存储拷贝的原对象属性方法
for(const key in obj){
if(obj[key] && typeof obj[key] === 'object'){
newObj[key] = cloneObj(obj[key])
}else{
newObj[key] = obj[key]
}
}
return newObj
}
let obj = {
name: 'jack',
age: 18,
fun: {
swiming: '游泳',
},
say: function () {
console.log('说话')
},
score: undefined,
}
let newObj = cloneObj(obj)
newObj.name = 'rose'
newObj.age = 20
newObj.score = 98
newObj.fun.swiming = '玩游戏'
console.dir(newObj)
console.dir(obj)