-
Notifications
You must be signed in to change notification settings - Fork 108
/
JS深拷贝的实现.js
47 lines (46 loc) · 1.26 KB
/
JS深拷贝的实现.js
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
// 1
function deepClone(origin, target) {
var target = target || {};
for(var key in origin) {
if(origin.hasOwnProperty(key)) {
if(Array.isArray(origin[key])) {
target[key] = [];
deepClone(origin[key], target[key]);
} else if (typeof origin[key] === 'object' && origin[key] !== null) {
target[key] = {};
deepClone(origin[key], target[key]);
}
target[key] = origin[key];
}
}
return target;
}
// 2
function type(obj) {
var typeString = Object.prototype.toString.call(obj);
return typeString.slice(8, typeString.length - 1);
}
function deepClone(origin, target) {
var target = target || {};
for(var key in origin) {
if(origin.hasOwnProperty(key)) {
target[key] = type(origin[key]) === 'Array' ?
deepClone(origin[key], []) :
type(origin[key]) === 'Object' ? deepClone(origin[key], {}) : origin[key];
}
}
return target;
}
// 3
function deeoClone(origin, target) {
return Object.assign(target, JSON.parse(JSON.stringify(origin)));
}
var origin = {
'a': [1,2,3],
'b': {
'c': 123,
'd': undefined
}
}
var target = {'e': 'Rainy', 'f': {}}
deepClone(origin, target);