浅拷贝:(原始值拷贝)
var obj = {
name: 'abc',
age: 123,
sex: 'female'
}
var obj1 = {}
function clone(origin, target) {
var target = target || {}; //防止用户未传入目标值
for(var prop in origin) {
target[prop] = origin[prop];
}
return target;
}
clolne(obj, obj1);
这种情况下改变 obj 的原始值,不影响 obj1,改变obj 中引用值的值,会影响 obj1
如果我们想要改变 obj 中引用值的值时不影响 obj1, 则需要用到深拷贝
深拷贝:(引用值拷贝)
var obj = {
name: 'abc',
age: 123,
card: ['visa', 'master'],
wife: {
name: 'bcd',
son: {
name: 'aaa'
}
}
}
var obj1 = {
}
//遍历对象
//1.判断是不是原始值
//2.判断是数组还是对象
//3.建立相应的数组或对象
//递归
function deepClone(origin, target){
var target = target || {},
toStr = Object.prototype.toString,
arrStr = "[object Array]";
for(var prop in origin){
if(origin.hasOwnProperty(prop)){
if(origin[prop] !== "null" && typeof(origin[prop] == "object"){
if(toStr.call(origin[prop]) == arrStr){
target[prop] = [];
}else{
target[prop] = {};
}
deepClone(origin[prop], target[prop]);
}else{
target[prop] = origin[prop];
}
}
}
return target;
}