675 对象的引用-浅拷贝-深拷贝

Posted Keep going

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了675 对象的引用-浅拷贝-深拷贝相关的知识,希望对你有一定的参考价值。

<!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>Document</title>
</head>

<body>

  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

  <!-- 1.对象的引用赋值 -->
  <script>
    // 对象是引用类型
    // const info = {name: "why", age: 18};
    // const obj = info;
    // info.name = "kobe";
    // console.log(obj.name);
  </script>

  <!-- 2.对象的浅拷贝 -->
  <script>
    const info = { name: "why", age: 18, friend: { name: "kobe" } };
    // const obj = Object.assign({}, info);

    // lodash
    const obj = _.clone(info);

    // info.name = "kobe";
    // console.log(obj.name);

    // info.friend.name = "james";
    // console.log(obj.friend.name);
  </script>

  <!-- 3.对象的深拷贝 -->
  <script>
    // _.cloneDeep(info)

    // const info = {name: "why", age: 18, friend: {name: "kobe"}};
    // const obj = JSON.parse(JSON.stringify(info)); // 生成一个新的对象
    // info.friend.name = "james";
    // console.log(obj.friend.name);
  </script>

  <!-- 我的补充 -->
  <script>
    const info2 = { name: "why", age: 18, friend: { name: "kobe" } };
    const obj2 = Object.assign({}, info2)
    console.log(info2)
    console.log(obj2)
    console.log(obj2 == info2) // false

    info2.name = \'哈哈哈\'
    console.log(info2.name)
    console.log(obj2.name)

    info2.friend.name = \'呵呵\'
    console.log(info2.friend.name)
    console.log(obj2.friend.name)
    console.log(obj2.friend === info2.friend) // true

    console.log(\'----------------\')

    const info3 = {
      name: "why",
      age: 18,
      friend: { name: "kobe" },
      reg: /\\d/,
      fn: function fn() {
        console.log(111)
      },
      date1: new Date()
    };

    const obj3 = JSON.parse(JSON.stringify(info3))
    console.log(info3)
    console.log(obj3)
    console.log(obj3 == info3) // false
    console.log(obj3.friend == info3.friend) // false
  </script>

</body>

</html>

以上是关于675 对象的引用-浅拷贝-深拷贝的主要内容,如果未能解决你的问题,请参考以下文章

实现浅拷贝与深拷贝

实现浅拷贝与深拷贝

深拷贝-浅拷贝

Python3 & 浅拷贝与深拷贝

深拷贝和浅拷贝

浅谈java浅拷贝和深拷贝