实现自己的深拷贝

  1. function deepCopy(obj) {
  2. let result = Array.isArray(obj) ? [] : {};
  3. for (let key in obj) {
  4. if (obj.hasOwnProperty(key)) {
  5. if (typeof obj[key] === "object") {
  6. result[key] = deepCopy(obj[key]);
  7. } else {
  8. result[key] = obj[key];
  9. }
  10. }
  11. }
  12. return result;
  13. }
  14. let array1 = [{ 1: "2" }, { 3: "4" }];
  15. let array2 = deepCopy(array6);
  16. console.log(array1[0] === array2[0]); //output false

Object.assign()和Object.create()

这两个函数能实现一层的深拷贝

Object.assign(targeObj,…sourceObjs):

可枚举属性的复制,返回根据targeObj

  1. //当source是一层的时候,Object.assign()方法能实现深拷贝
  2. const target = [1,2];
  3. const source = [3,4];
  4. const returnedTarget = Object.assign(target, source)
  5. target[0] = 5
  6. console.log(source);//output: [3,4]
  7. console.log(target);//output: [5,4]
  8. console.log(returnedTarget);//output: [5,4]
  9. //当source有多层时,从第二层开始后面都是浅拷贝了
  10. const target = [1,2];
  11. const source = [3,[5,6]];
  12. const returnedTarget = Object.assign(target, source)
  13. target[1][0] = 7
  14. console.log(source);//output: [3,[7,6]]
  15. console.log(target);//output: [3,[7,6]]
  16. console.log(returnedTarget);//output: [3,[7,6]]

Object.create(propObj[,propertiesObject]):

创建一个新对象,并提供proto,返回这个新对象

  1. //当obj1是一层的时候(obj1可以是数组),Object.create()方法能实现深拷贝
  2. const obj1 = {
  3. a:1,
  4. b:2
  5. };
  6. const obj2 = Object.create(obj1);
  7. obj2.a = 3;
  8. obj2.b = 4;
  9. console.log(obj1.a)//output:1
  10. console.log(obj1.b)//output:2
  11. console.log(obj2.a)//output:3
  12. console.log(obj2.b)//output:4
  13. //当obj1有多层时(obj1可以是数组),从第二层开始后面都是浅拷贝了
  14. const obj1 = {
  15. a:{x:'x'},
  16. b:2
  17. };
  18. const obj2 = Object.create(obj1);
  19. obj2.a.x = 'hasBeenChanged' ;
  20. obj2.b = 4;
  21. console.log(obj1.a.x)//output:hasBeenChanged
  22. console.log(obj1.b)//output:2
  23. console.log(obj2.a.x)//output:hasBeenChanged
  24. console.log(obj2.b)//output:4


JSON.stringfy()和JSON.parse()

进行序列化和反序列化能够做到深拷贝

  1. const obj1 = {a:1,b:2,c:{x:8,y:9}}
  2. const obj2 = JSON.parse(JSON.stringify(obj1))
  3. obj2.c.x=10
  4. console.log(obj1)//output: {a:1,b:2,c:{x:8,y:9}}
  5. console.log(obj2)//output:{a:1,b:2,c:{x:10,y:9}}

jQuery的extend方法

$.extend(Boolean,targetObj,sourceObjs),第一个参数默认为false表示浅拷贝,改为true表示深拷贝

  1. const $ =require('jquery')
  2. const obj1 = {
  3. a: 1,
  4. b: { d: { e: 1 } },
  5. c: [1, 2, 3]
  6. };
  7. const obj2 = $.extend(true, {}, obj1);
  8. obj2.b.d.e=4;
  9. console.log(obj1)//output:{a:1,b:{d:{e:1},c:[1,2,3]}
  10. console.log(obj2)//output:{a:1,b:{d:{e:4},c:[1,2,3]}

lodash的cloneDeep方法

_.cloneDeep(sourceObj),返回一个targetObj

  1. const _ = require('lodash');
  2. const obj1 = {
  3. a: 1,
  4. b: { d: { e: 1 } },
  5. c: [1, 2, 3]
  6. };
  7. const obj2 = _.cloneDeep(obj1);
  8. obj2.b.d.e=4;
  9. console.log(obj1)//output:{a:1,b:{d:{e:1},c:[1,2,3]}
  10. console.log(obj2)//output:{a:1,b:{d:{e:4},c:[1,2,3]}