总体思路:
- 判断对象当中的值为引用值还是原始值
- 如果是引用值,判断是数组还是对象,如果是原始值直接copy
- 递归
注意:不要忘了排除null,因为typeof null = 'object'
function deepClone (origin,target) {
var target = target || {};
var toStr = Object.prototype.toString;
var typeArr = '[object Array]';
for (var prop in origin) {
//判断是引用值还是原始值
if (origin[prop] != null && typeof origin[prop] == 'object') {
// 判断是数组还是对象
if (toStr.call(origin[prop]) == typeArr) {
target[prop] = [];
} else {
target[prop] = {};
}
deepCopy(origin[prop],target[prop])
} else {
target[prop] = origin[prop];
}
}
return target;
}