//浅拷贝var o1 = { a: 10, b: 20, c: 30 };var o2 = o1;o2.a = 100;console.log(o1);//深拷贝var o1 = { a: 10, b: 20, c: 30 };var o2 = { a: o1.a, b: o1.b, c: o1.c };o2.a = 100;console.log(o1);//深拷贝 只适用于一维数组var o1 = { a: 10, b: 20, c: 30 };var o2 = { ...o1 };o2.a = 100;console.log(o1);//简单深拷贝,将对象转成json字符串再转回来var o1 = { a: { d: 40 }, b: 20, c: 30 };var o2 = JSON.parse(JSON.stringify(o1));o2.a.d = 100;console.log(o1);//多维数组var o1 = { a: { d: 40 }, b: 20, c: 30 };var o2 = { ...o1 };o2.a.d = 88;console.log(o1);//Object.assign 能够实现一层深拷贝var o1 = { name: "Gucci", age: 13, gender: "female", hobby: { a: 'Chinese', b: 'Math', c: 'English' }};var o2 = Object.assign({}, o1);o2.hobby.a = "Math";o1.age = 1000;console.log(o1);//终极大杀器 递归复制实现深拷贝//注意typeof []结果为objecttypeof []"object"typeof {}"object"typeof "111""string"typeof null"object"function deepClone(obj){ let objClone = Array.isArray(obj)?[]:{}; if(obj && typeof obj==="object"){ for(key in obj){ if(obj.hasOwnProperty(key)){ //判断ojb子元素是否为对象,如果是,递归复制 if(obj[key]&&typeof obj[key] ==="object"){ objClone[key] = deepClone(obj[key]); }else{ //如果不是,简单复制 objClone[key] = obj[key]; } } } } return objClone;} let a=[1,2,3,4], b=deepClone(a);a[0]=2;console.log(a,b);
//运算结果按顺序打印{ a: 100, b: 20, c: 30 }{ a: 10, b: 20, c: 30 }{ a: 10, b: 20, c: 30 }{ a: { d: 40 }, b: 20, c: 30 }{ a: { d: 88 }, b: 20, c: 30 }{ name: 'Gucci', age: 1000, gender: 'female', hobby: { a: 'Math', b: 'Math', c: 'English' } }[ 2, 2, 3, 4 ] [ 1, 2, 3, 4 ]