var dataOrigin = [
{
name: 'abc',
age: 18,
show: function() {
console.log('hi')
},
hobby: ['football', 'book', 'eat']
},
{
name: 'aaa',
age: 23,
show: function() {
console.log('hello')
},
hobby: ['book', 'code', 'run']
}
];
var dataTarget = deepClone(dataOrigin, dataTarget);
console.log(dataTarget);
dataTarget[0].name = 'bbb';
console.log(dataOrigin);
function deepClone(origin, target) {
var target = target;
// [object Object]
var isObj = Object.prototype.toString();
// [object Array]
var isArr = Object.prototype.toString.call([]);
// 对象
if(Object.prototype.toString.call(origin) === isObj) {
target = target || {};
}
// 数组
else if(Object.prototype.toString.call(origin) === isArr) {
target = target || [];
}
for(var prop in origin) {
if(origin.hasOwnProperty(prop)) {
var _origin = origin[prop];
// 引用类型
if(_origin !== null && typeof _origin === 'object') {
// object
if(Object.prototype.toString.call(_origin) === isObj) {
target[prop] = {};
}
// array
else if(Object.prototype.toString.call(_origin) === isArr) {
target[prop] = [];
}
deepClone(_origin, target[prop]);
}
// 基本类型
else {
target[prop] = _origin;
}
}
}
return target;
}
在一些情况下还有一些简单粗暴的解决办法,参考:
JSON.parse(JSON.stringfy())
进行深拷贝方法小结
关于JSON.parse(JSON.stringify(obj))
实现深拷贝应该注意的坑
JavaScript之对象序列化详解