应用场景:在复杂类型的赋值运算中使用(**Array,Object**)

一、浅拷贝:即传值又传址

1-1、数据为简单数据类型

  1. var arr=[1,2,3]
  2. var b=arr
  3. b.push(4)
  4. console.log(arr) // 1,2,3,4

1-2、数据每项是复杂数据类型

  1. var arr = [{name:"zheng"},{name:"zhang"},{name:"li"}]
  2. var res = [...arr]
  3. res[0].name="huang" // arr变了
  4. res.push({name:"vue"})
  5. console.log(arr) // [{name:"huang"},{name:"zhang"},{name:"li"}]

八、深拷贝、浅拷贝 - 图1

二、深拷贝:只传值不传址

2-1、数组为简单数据类型

  1. var res=[1,2,3]
  2. 1
  3. var c=[]
  4. res.forEach(item=>{
  5. c.push(item)
  6. })
  7. c.push(4)
  8. console.log(res); //[1,2,3]
  9. console.log(c); // [1,2,3,4]
  10. 2
  11. c=[...res]
  12. c.push(4)
  13. console.log(res); //[1,2,3]
  14. console.log(c); // [1,2,3,4]
  15. 3
  16. c=res.slice(0,)
  17. c.push(4)
  18. console.log(res); //[1,2,3]
  19. console.log(c); // [1,2,3,4]
  20. 4
  21. c = [].concat(res)
  22. c.push(4)
  23. console.log(res); //[1,2,3]
  24. console.log(c); // [1,2,3,4]

2-2、对象属性是简单数据类型

  1. var obj = {name:"cheng",age:18}
  2. // var a = {...obj}
  3. var a = Object.assign({},obj)
  4. obj.id = 100;
  5. console.log(a) // {name:"cheng",age:18}

2-3、每项为复杂数据类型

  1. var obj={name:{name:"xuan"}}
  2. function deepClone(obj) {
  3. let result;
  4. if (obj instanceof Array || typeof obj == "object") {
  5. if (obj instanceof Array) {
  6. result = [];
  7. }
  8. else if (typeof obj == "object") {
  9. result = {};
  10. }
  11. for (let key in obj) {
  12. result[key] = deepClone(obj[key]);
  13. }
  14. return result;
  15. }
  16. else {
  17. return obj
  18. }
  19. }
  20. var res=deepClone(obj)
  21. console.log(res)