手写JS深拷贝

时间:2021-07-11
本文章向大家介绍手写JS深拷贝,主要包括手写JS深拷贝使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JS深拷贝</title>
</head>
<body>
  
</body>
<script>
  let obj = {
    name: '张三',
    age:22,
    arr: [1,2,'dadas'],
    where: {
      country1: '中国',
      country2: '府谷',
    }
  }

  function deepClone(obj) {
    if(obj === null || typeof obj !== 'object') {
      return obj;
    }
    let result;
    if(obj instanceof Array) {
      result = []
    } else {
      result = {}
    }
    for(let key in obj) {
      if(obj.hasOwnProperty(key)) {
        result[key] = deepClone(obj[key])
      }
    }
    return result
  }

  let newObj =  deepClone(obj);
  console.log(newObj);
  newObj.name = 999;
  console.log(newObj);
  console.log(obj);


</script>
</html>

  

原文地址:https://www.cnblogs.com/chailuG/p/14999969.html