特点:只传值

  1. <script>
  2. //遇到复杂数据类型(array,object)如何实现深拷贝
  3. var obj = {name:{name:"张"}};
  4. function deepClone(obj){
  5. //1.能够识别数组和对象
  6. let result;
  7. if(typeof obj =="number" || obj == null || typeof obj == "boolean" ||typeof obj == "string"){
  8. return obj;
  9. }
  10. if(obj instanceof Array || typeof obj == "object"){
  11. //2.对拷贝的值作初始值的设定
  12. if(obj instanceof Array){
  13. result = [];
  14. }else if(typeof obj == "object"){
  15. result = {};
  16. }
  17. //3.需要将obj克隆到result中
  18. for(let key in obj){
  19. result[key] = deepClone(obj[key]);
  20. }
  21. return result;
  22. }else {
  23. return obj;
  24. }
  25. }
  26. var res = deepClone(obj);
  27. console.log(res);
  28. /*
  29. result = {name:deepClone({name:"cheng"})}
  30. result = {name:{name:deepClone("cheng")}}
  31. result = {name:{name:"cheng"}}
  32. */
  33. </script>

image.png