浅克隆
只能拷贝原始值,如果存在引用值,拷贝的是引用地址。origin 更改值后 target还是会被改变
function clone(origin, target) {
var target = target || {};
for (var prop in origin) {
target[prop] = origin[prop];
}
return target;
}
var obj = {
name: 'xiaoming',
age: 19
}
var obj1 = {};
clone(obj, obj1);
深度克隆
无论原始值还是引用值,都进行copy 互不影响
// 1. 遍历对象 for in
// 2. 判断是不是原始值 typeof
// 3. 判断是数组还是对象 toString
// 3. 建立相应的数组或对象
// 4. 递归
function deepClone(origin, target) {
var target = target || {};
var toStr = Object.prototype.toString;
for (var key in origin) {
if (origin.hasOwnProperty(key)) {
var res = toStr.call(origin[key]);
if (res === '[object Object]') {
target[key] = {};
deepClone(origin[key], target[key]);
} else if (res === '[object Array]') {
target[key] = [];
deepClone(origin[key], target[key]);
} else {
target[key] = origin[key];
}
}
}
return target;
}
var obj = {
name: 'xiaoming',
age: 28,
card: ['visa', 'master'],
wife: {
name: 'xiaozhang',
son: {
name: 'xiaoxiaoming'
}
}
}
var obj1 = {};
deepClone(obj, obj1);