-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path15_引用类型深拷贝_JSON.html
48 lines (40 loc) · 1.1 KB
/
15_引用类型深拷贝_JSON.html
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
/**
* 引用类型的深拷贝
* @author cgh
* @time 2018-04-09
* @param {[Object]} object [description]
* @return {[Object]} [返回一个新对象]
*/
function deepCopy(obj) {
if (typeof obj !== 'object') {
return false;
}
var result = JSON.parse(JSON.stringify(obj));
return result;
}
// 使用JSON来完成深拷贝
// 注意,由于JSON无法序列化函数,所以拷贝后函数会被丢弃
// 建议要进行深拷贝的对象最好是数据对象,不要包含函数
var obj = {
a: 1,
test: [2, 3],
// foo将被丢失
foo: function() {
console.log(bar)
}
};
var obj2 = deepCopy(obj);
console.log(JSON.stringify(obj), JSON.stringify(obj2), obj === obj2);
obj2.test[0] = '我改变了';
console.log(JSON.stringify(obj), JSON.stringify(obj2));
</script>
</body>
</html>