茗空间

两种javascript深拷贝的方法

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function deepCopy(obj) {
if (!obj || typeof obj !== 'object') return obj;
var target = isPlainObject(obj) ? {} : [],
property, val;
for (var key in obj) {
val = obj[key];
// 防止循环引用
if (val === obj) continue;
if (Array.isArray(val) || isPlainObject(val)) {
target[key] = deepCopy(val);
} else {
target[key] = val;
}
}
return target;
}
function isPlainObject(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}

非递归

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
function deepCopy(obj) {
if (!obj || typeof obj !== 'object') return obj;
var target = isPlainObject(obj) ? {} : [],
auxlity = [
[target, obj]
];
while (auxlity.length) {
var item = auxlity.shift(),
to = item[0],
from = item[1];
for (var key in from) {
var prop = from[key];
// 防止循环引用
if (from === prop) continue;
if (Array.isArray(prop)) {
to[key] = [];
auxlity.push([to[key], prop]);
} else if (isPlainObject(prop)) {
to[key] = {};
auxlity.push([to[key], prop]);
} else {
to[key] = prop;
}
}
}
return target;
}
function isPlainObject(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}