对象深拷贝的三种方法

A1:JSON方法实现

  1. //_tmp和result是相互独立的,没有任何联系,有各自的存储空间。
  2. let deepClone = function (obj) {
  3. let _tmp = JSON.stringify(obj);//将对象转换为json字符串形式
  4. let result = JSON.parse(_tmp);//将转换而来的字符串转换为原生js对象
  5. return result;
  6. };
  7. let obj1 = {
  8. weiqiujaun: {
  9. age: 20,
  10. class: 1502
  11. }
  12. };
  13. deepClone(obj1);

A2:用for…in实现遍历和复制

  1. // 定义拷贝方法
  2. function deepClone(obj) {
  3. let result = typeof obj.splice === "function" ? [] : {};
  4. if (obj && typeof obj === 'object') {
  5. for (let key in obj) {
  6. if (obj[key] && typeof obj[key] === 'object') {
  7. //如果对象的属性值为object的时候,递归调用deepClone
  8. result[key] = deepClone(obj[key]);
  9. } else {
  10. //如果对象的属性值不为object的时候
  11. result[key] = obj[key];
  12. }
  13. }
  14. return result;
  15. }
  16. return obj;
  17. }
  18. // 定义对象
  19. let testArray = ["a", "b", "c", "d"];
  20. let testObj = {
  21. sex: "girl",
  22. age: 22,
  23. family: {brother: "wei"}
  24. }
  25. // 调用拷贝方法
  26. deepClone(testArray);
  27. deepClone(testObj);

A3:利用数组的Array.prototype.forEach进copy

相关api:Object.getOwnPropertyDescriptor()Object.getOwnPropertyNames()

  1. let deepClone = function (obj) {
  2. let copy = Object.create(Object.getPrototypeOf(obj));
  3. let propNames = Object.getOwnPropertyNames(obj);
  4. propNames.forEach(function (items) {
  5. let item = Object.getOwnPropertyDescriptor(obj, items);
  6. Object.defineProperty(copy, items, item);
  7. });
  8. return copy;
  9. };
  10. let testObj = {
  11. sex: "girl",
  12. age: 22,
  13. family: {brother: "wei"}
  14. }
  15. deepClone(testObj);

对象浅拷贝方法

使用object.assign方法

  1. let target=[];
  2. let testArr=[2,3,5,8];
  3. Object.assign(target,testArr);
  4. console.log(target);
  5. testArr.push(8);
  6. console.log("我是原来的"+target+",我是现在的"+testArr);

[

](https://blog.csdn.net/qq_39083004/article/details/80206336)

函数拷贝方法

  1. function targets () {
  2. return { a : 2 }
  3. }
  4. const copys = new Function('return '+ targets.toString())()