代码如下
function deepCopy(o, n) {
for (var i in n) {
if (typeof n[i] == 'object') {
o[i] = n[i].constructor == Array ? [] : {};
deepCopy(o[i], n[i]);
} else {
o[i] = n[i];
}
}
return o;
}
测试:
var a = {};
var b = {
num: 30,
arr: [9, 23],
obj: {
'year': 2017,
"lover": "qingjie"
}
};
deepCopy(a, b);
a.arr.push(3);
console.log(a);
/*
{
num: 30,
arr: [ 9, 23 ,3],
obj: {
year: 2017,
lover: 'qingjie'
}
}
*/
console.log(b);
/*
{
num: 30,
arr: [ 9, 23 ],
obj: {
year: 2017,
lover: 'qingjie'
}
}
*/
网友评论