我们首先稍微复习一下有关JS中的数据类型及相关知识点

1-简单数据类型:Undefined,Null,Boolean,Symbol,Number,String

2-复杂数据类型:对象

简单数据类型保存在栈内存中

复杂数据类型即引用类型,保存于堆内存中;引用的类型值实际为指向对象的指针

这与我们今天所需要讲到的深浅拷贝有关

浅拷贝

相当于我们复制了该对象或数组,然而该“指针”仍然指向原本内存空间

1
2
3
4
5
6
7
8
var obj = {
name:'wsscat',
age:0
}
var obj2 = obj;
obj2['c'] = 5;
console.log(obj);//Object {name: "wsscat", age: 0, c: 5}
console.log(obj2);////Object {name: "wsscat", age: 0, c: 5}

我们可以看到,当我们改变obj2的[‘c’]时候,obj1会受到其影响

深拷贝

数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1-slice():

var arr = ['wsscat', 'autumns', 'winds'];
var arrCopy = arr.slice(0);
arrCopy[0] = 'tacssw'
console.log(arr)//['wsscat', 'autumns', 'winds']
console.log(arrCopy)//['tacssw', 'autumns', 'winds']

2-concat():

var arr = ['wsscat', 'autumns', 'winds'];
var arrCopy = arr.concat();
arrCopy[0] = 'tacssw'
console.log(arr)//['wsscat', 'autumns', 'winds']
console.log(arrCopy)//['tacssw', 'autumns', 'winds']

对象

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
28
29
30
31
32
33
34

1-新建对象后遍历实现
var obj = {
name:'wsscat',
age:0
}
var obj2 = new Object();
obj2.name = obj.name;
obj2.age = obj.age

obj.name = 'autumns';
console.log(obj);//Object {name: "autumns", age: 0}
console.log(obj2);//Object {name: "wsscat", age: 0}

2-封装好方法进行对象拷贝处理
var obj = {
name: 'wsscat',
age: 0
}
var deepCopy = function(source) {
var result = {};
for(var key in source) {
if(typeof source[key] === 'object') {
result[key] = deepCopy(source[key])
} else {
result[key] = source[key]
}
}
return result;
}
var obj3 = deepCopy(obj)
obj.name = 'autumns';
console.log(obj);//Object {name: "autumns", age: 0}
console.log(obj3);//Object {name: "wsscat", age: 0}

"深浅拷贝.jpg"