-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathjs对象和数组深克隆.html
78 lines (73 loc) · 1.95 KB
/
js对象和数组深克隆.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>js对象和数组深克隆</title>
</head>
<body>
</body>
<script type="text/javascript">
function clone(obj) {
var o;
if (typeof obj == "object") {
if (obj === null) {
o = null;
} else {
if (obj instanceof Array) {
o = [];
for (var i = 0, len = obj.length; i < len; i++) {
o.push(this.clone(obj[i]));
}
} else {
o = {};
for (var j in obj) {
o[j] = this.clone(obj[j]);
}
}
}
} else {
o = obj;
}
return o;
}
</script>
<script>
function typeOf(obj) {
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
}
return map[Object.prototype.toString.call(obj)];
}
// deepCopy
function deepCopy(data) {
const dataType = typeOf(data);
let result
if (dataType === 'array') {
result = []
} else if (dataType === 'object') {
result = {}
} else {
return data
}
if (dataType === 'array') {
for (let i = 0; i < data.length; i++) {
result.push(deepCopy(data[i]));
}
} else if (t === 'object') {
for (let i in data) {
result[i] = deepCopy(data[i]);
}
}
return result
}
</script>
</html>