# 第一步:js深拷贝和浅拷贝的概念和区别。
1.浅拷贝
拷贝就是把父对像的属性,全部拷贝给子对象。此时子对象拷贝的是父对象的地址,子父对象相互影响。
2.深拷贝
就是把父对象的属性中的值拷贝给子对象此时不论父对象如何改变都不会再影响到子对象。
# 第二步:测试浅拷贝。我们借助于谷歌浏览器控制台实现浅拷贝的测试,
首先声明对象:
var father={
familyName:"张"
};
var son={};
1
2
3
4
5
2
3
4
5
拷贝son=father此时打印,son和father的familyName都是张
将father的familyName改为“李”,则son的familyName也变为了“李”。
这就是浅拷贝,拷贝的是存储变量的地址会互相影响。
# 第三步:浅拷贝的实现
第一种:借助于js的JSON对象的两个函数
JSON.stringify(father)将一个json对象转为json字符串
JSON.parse(str)将一个json字符串转为json对象
它的实现原理是现将对象转为一个基本数据类型,在执行拷贝,不过这个只是适用于json格式的数据对其它情况不一定都能满足。测试如下:
var father={familyName:"张"};var son={};
son = JSON.parse(JSON.stringify(father));
father.familyName="李"
son.familyName
1
2
3
4
5
6
7
2
3
4
5
6
7
# 第四步:借助于for 循环实现数组的深拷贝
具体代码和实现:如下
var father = [1,2,3,4,5]
var son = copyArr(father)
function copyArr(father) {
let res = []
for (let i = 0; i < arr.length; i++) {
res.push(father[i])
}
return res
}
console.log(father)
console.log(son)
father[2] = 5
console.log(father)
console.log(son)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 第五步:借助于slice 方法实现数组的深拷贝
具体代码如下所示:
var father = [1,2,3,4,5]
var son = father.slice(0)
console.log(father)
console.log(son)
father[2] = 5
console.log(father)
console.log(son)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 第六步:借助于concat 方法实现数组的深拷贝
具体代码如下所示:
var father = [1,2,3,4,5]
var son = father.concat()
console.log(father)
console.log(son)
father[2] = 5
console.log(father)
console.log(son)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 第七步:使用ES6扩展运算符实现数组的深拷贝
具体代码如下所示:
var father = ['张三','李四','刘德华','周润发']
var [ ...son ] = father
console.log(father)
console.log(son)
father[2] = 5
console.log(father)
console.log(son)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13