## 我理解的浅拷贝和深拷贝

浅拷贝的方法：

1.直接赋值：

``` var obj1 = {a: 1, b: 2};

var obj2 = obj1;

obj2.b = 22;

console.log(obj1.b); // 22```

2.Object.assign

```var obj1 = {a: 1, b: 2};
var obj2 = {c: 3};
Object.assign(obj1, obj2);
console.log(obj1) // {a: 1, b: 2, c: 3}
obj2.c = 4;
console.log(obj1.c) // 3```

```var obj1 = {a: 1, b: 2};
var obj2 = {c: {z: 3}};
Object.assign(obj1, obj2);
console.log(obj1); // {a: 1, b: 2, c: {z: 3}}
console.log(obj2); // {c: {z: 3}}
obj2.c.z = 4;
console.log(obj1.c.z); // 4;```

3.通过对象扩展运算符 （{ ...obj }）

```var obj1 = {
a: 1,
b: 2,
c: {
z: 3
}
};
var obj2 = {...obj1};
console.log(obj2); // { a: 1, b: 2, c: { z: 3 } }

obj1.a = 11;
console.log(obj2.a);  // 1

obj1.c.z = 33;
console.log(obj2.c.z); // 33```

4.通过数组的slice方法

```var arr1 = [1, [2, 3], 4];
var arr2 = arr1.slice();

console.log(arr2); // [1, [2, 3], 4]

arr1[0] = 11;
console.log(arr2[0]); // 1; 貌似深拷贝了，但是：

arr1[1][0] = 22;
console.log(arr2); // [1, [22, 3], 4;  还是太年轻啊！！！```

5.通过数组的concat方法。

```var arr1 = [1, [2, 3], 4];
var arr2 = arr1.concat();

console.log(arr2); //  [1, [2, 3], 4]

arr1[0] = 11;
console.log(arr2[0]); // 1;

arr1[1][0] = 22;
console.log(arr2[1][0]); // 22```

1. JSON.stringify() + JSON.parse();

```var obj1 = {
a: 1,
b: 2,
c: {
z: 3
}
};

var obj2 = JSON.parse(JSON.stringify(obj1));
console.log(obj2); // {a: 1, b: 2, c: {z: 3}}```
`obj1.c.z = 33; console.log(obj2.c.z); // 3`

```var obj1 = {
a: 1,
b: 'b',
c: [1,2,3],
u: undefined,
s: Symbol('s'),
f: function() {
console.log(123);
}
};

var obj2 = JSON.parse(JSON.stringify(obj1));

console.log(obj2); // {a: 1, b: 'b', c: [1, 2, 3]}```

2.递归：

```var deepCopy = function(obj) {
if (typeof obj !== 'object') return;
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}```