未整理—js中的深拷贝

第一次实现:

function deepCopy(data) {
  let c = data.constructor === 'Array'?[]:{};
  for (let key in data)     {
    if (data.hasOwnProperty(key)) {
      if (typeof data[key] === 'Object') {
        c[key] = deepCopy(data[key]);
      } else {
        c[key] = data[key];
      } 
    }
  }
  return c;
}
 

var obj = {
  a: 1,
  b: 2,
  c: {
    d: 10,
    e: 11
  }
}

let obj2 = deepCopy(obj);
obj.a = 'aaaa';

obj2.b = 'bbbb';
console.log(obj);
console.log(obj2);



var personInfo = {
name : 'zhang',
age: 26,
family: {
 province: 'hunan',
 city: 'changsha',
}
};
var copyPerson = deepCopy1(personInfo);
personInfo.name = 'shaunZh';
personInfo.family.province = 'gd';
personInfo.family.city = 'yuenan';
console.log('modify personInfo: ');
console.log(personInfo);
console.log('get copyPerson: ');
console.log(copyPerson);

你的深拷贝函数的值,有考虑过以下值吗?symbol,function,正则,数组,undefined,null,循环引用的对象?

你可能感兴趣的:(未整理—js中的深拷贝)