平常我们都是用JSON来做复杂数据类型的拷贝,但是如果遇到有undefined,NaN,函数这些数据,使用JSON就会被转译,达不到期望的拷贝效果,所以如果有以上情况就需要是用递归来拷贝啦
<script>
function deepCopy(current, additive) {
// 深拷贝函数
// 参数一:需要添加拷贝的数据
// 参数二:被拷贝的数据
if ((typeof additive) != 'object') {
current = additive;
} else {
if ((typeof current) == 'undefined' || current.constructor != additive.constructor) {
current = new (additive.constructor);
}
function recur(c, a) {
for (let key in a) {
if ((typeof a[key]) == 'object') {
if ((typeof c[key]) == 'undefined' || c[key].constructor != a[key].constructor) {
c[key] = new (a[key].constructor);
}
recur(c[key], a[key]);
} else {
c[key] = a[key];
}
}
}
recur(current, additive);
}
return current;
}
let data = {
a: [1, 2, 3],
b: '55'
}
let state = {
a: '1',
b: {
c: '2',
d: [3, {
e: '4'
}]
},
s: function (v) {
return v + 2;
}
}
// 测试一下
// 将state拷贝给data
data = deepCopy(data, state);
console.log(data);
console.log(data.s(2));
</script>