1.浅拷贝

既传值也传址

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

2.深拷贝

只传值

  1. var arr = [1,2,3];
  2. var b = arr.slice(0,);
  1. arr.forEach(item=>{
  2. b.push(item);
  3. })
  1. var arr = [{name:"cheng"},{name:"zhang"},{name:"li"}];
  2. var res = [...arr];
  3. res[0].name="huang";
  4. res.push({name:"vue"});
  5. console.log(arr);
  1. var arr = [{name:"cheng"},{name:"zhang"},{name:"li"}];

第十二章 深拷贝和浅拷贝 - 图1

  1. var arr = [{name:"cheng"},{name:"zhang"},{name:"li"}];
  2. var res = [...arr];

第十二章 深拷贝和浅拷贝 - 图2

遇到复杂类型(array+object)如何实现深拷贝

  1. var obj = {name:{name:"cheng"}};
  2. function deepClone(obj){
  3. /* 1.能够识别数组和对象了 */
  4. let result;
  5. if(typeof obj=="number" || obj == null || typeof obj=="boolean"||typeof obj=="string"){
  6. return obj;
  7. }
  8. if(obj instanceof Array || typeof obj == "object"){
  9. /* 2.对拷贝的值作初始值得设定 */
  10. if(obj instanceof Array){
  11. result = [];
  12. }else if(typeof obj =="object"){
  13. result = {};
  14. }
  15. /* 3.需要将obj克隆到result中 */
  16. for(let key in obj){
  17. result[key] = deepClone(obj[key]);
  18. }
  19. return result;
  20. }
  21. }
  22. var res = deepClone(obj);
  23. console.log(res)

简单数据类型实现深拷贝

  1. 1. {...obj}<br /> 2. Object.assign()
  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);

3.vue深拷贝

  1. name:<input type="text" v-model="newItem.name">
  2. id:<input type="text" v-model="newItem.id">
  3. <button @click="doAdd">添加</button>
  4. <div v-for="item of arr">
  5. {{item.name}}
  6. </div>
  1. new Vue({
  2. el:"#app",
  3. data:{
  4. newItem:{
  5. name:"",
  6. id:""
  7. },
  8. arr:[
  9. {name:"vue",id:1001},
  10. {name:"html",id:1001},
  11. {name:"css",id:1001}
  12. ]
  13. },
  14. methods:{
  15. doAdd(){
  16. var res = {...this.newItem}
  17. this.arr.push(res)
  18. }
  19. }
  20. })