区分
B复制了A的值,如果A被修改,B的值也被改变,那就是浅拷贝。
如果B的值没有跟着修改,那就是深拷贝
深浅拷贝的方式
1、遍历赋值
2、Object.create()
3、JSON.parse()和JSON.stringify()
浅拷贝-遍历
let a = {name:"jack",obj:{str:"ccc",arr:[1,2,3]},arr:[4,5,6]}let b = {};for(let i in a){b[i] = a[i];} // console.log(a);a.arr[1] = "aaa";console.log(b);
深拷贝-递归
let a = {name:"jack",obj:{str:"ccc",arr:[1,2,3]},arr:[4,5,6]} function deepclone(startobj,endobj){let obj = endobj || {};for(let i in startobj){if(typeof startobj[i] === "object"){obj[i] = startobj[i].constractor === Array ? [] : {};deepclone(startobj[i],obj[i]);}else{obj[i] = startobj[i];}}return obj;} let b = deepclone(a);console.log(a);console.log(b);a.obj.str = "nerwwww";console.log(a);console.log(b);
深拷贝-JSON.parse、JSON.stringfy
let a = {name:"jack",obj:{str:"ccc",arr:[1,2,3]},arr:[4,5,6]} let b = JSON.parse(JSON.stringify(a)); console.log(a);console.log(b);a.obj.str = "nerwwww";console.log(a);console.log(b);