• JSON.parse(JSON.stringify()) 实现对对象的深拷贝


    JSON.parse(JSON.stringify(obj))我们一般用来深拷贝,其过程说白了 就是利用JSON.stringify 将js对象序列化(JSON字符串),再使用JSON.parse来反序列化(还原)js对象;序列化的作用是存储(对象本身存储的只是一个地址映射,如果断电,对象将不复存在,因此需将对象的内容转换成字符串的形式再保存在磁盘上 )和传输(例如 如果请求的Content-Typeapplication/x-www-form-urlencoded,则前端这边需要使用qs.stringify(data)来序列化参数再传给后端,否则后端接受不到; ps: Content-Typeapplication/json;charset=UTF-8或者 multipart/form-data 则可以不需要 );我们在使用 JSON.parse(JSON.stringify(xxx))时应该注意一下几点:
    1、如果obj里面有时间对象,则JSON.stringify后再JSON.parse的结果,时间将只是字符串的形式。而不是时间对象;

          var test = {
            name: 'a',
            date: [new Date(1536627600000), new Date(1540047600000)],
          };
    
          let b;
          b = JSON.parse(JSON.stringify(test))
    
     
    test 结果.png
     
    b的结果
     
    测试b和test类型

    2、如果obj里有RegExp、Error对象,则序列化的结果将只得到空对象;

          const test = {
            name: 'a',
            date: new RegExp('\\w+'),
          };
          // debugger
          const copyed = JSON.parse(JSON.stringify(test));
          test.name = 'test'
          console.error('ddd', test, copyed)
    
     
    image.png

    3、如果obj里有函数,undefined,则序列化的结果会把函数或 undefined丢失;

          const test = {
            name: 'a',
            date: function hehe() {
              console.log('fff')
            },
          };
          // debugger
          const copyed = JSON.parse(JSON.stringify(test));
          test.name = 'test'
          console.error('ddd', test, copyed)
    
     
    image.png
     
    image.png

    4、如果obj里有NaN、Infinity和-Infinity,则序列化的结果会变成null


     
    image.png

    5、JSON.stringify()只能序列化对象的可枚举的自有属性,例如 如果obj中的对象是有构造函数生成的, 则使用JSON.parse(JSON.stringify(obj))深拷贝后,会丢弃对象的constructor;

          function Person(name) {
            this.name = name;
            console.log(name)
          }
    
          const liai = new Person('liai');
    
          const test = {
            name: 'a',
            date: liai,
          };
          // debugger
          const copyed = JSON.parse(JSON.stringify(test));
          test.name = 'test'
          console.error('ddd', test, copyed)
    
    
     
    image.png

    6、如果对象中存在循环引用的情况也无法正确实现深拷贝;

    以上,如果拷贝的对象不涉及上面讲的情况,可以使用JSON.parse(JSON.stringify(obj))实现深拷贝,但是涉及到上面的情况,可以考虑使用如下方法实现深拷贝:

     function  deepClone(data) {
          const type = this.judgeType(data);
          let obj;
          if (type === 'array') {
            obj = [];
          } else if (type === 'object') {
            obj = {};
          } else {
        // 不再具有下一层次
            return data;
          }
          if (type === 'array') {
            // eslint-disable-next-line
            for (let i = 0, len = data.length; i < len; i++) {
              obj.push(this.deepClone(data[i]));
            }
          } else if (type === 'object') {
            // 对原型上的方法也拷贝了....
            // eslint-disable-next-line
            for (const key in data) {
              obj[key] = this.deepClone(data[key]);
            }
          }
          return obj;
        },
    
    
    function  judgeType(obj) {
      // tostring会返回对应不同的标签的构造函数
          const toString = Object.prototype.toString;
          const map = {
            '[object Boolean]': 'boolean',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Function]': 'function',
            '[object Array]': 'array',
            '[object Date]': 'date',
            '[object RegExp]': 'regExp',
            '[object Undefined]': 'undefined',
            '[object Null]': 'null',
            '[object Object]': 'object',
          };
          if (obj instanceof Element) {
            return 'element';
          }
          return map[toString.call(obj)];
        },
    
    来源:https://www.cnblogs.com/sweet-ice/p/10583192.html
  • 相关阅读:
    Django的是如何工作的
    Robot Framework自动化测试(五)--- 开发系统关键字
    Swarm 如何存储数据?- 每天5分钟玩转 Docker 容器技术(103)
    如何滚动更新 Service?- 每天5分钟玩转 Docker 容器技术(102)
    Service 之间如何通信?- 每天5分钟玩转 Docker 容器技术(101)
    神奇的 routing mesh
    如何访问 Service?- 每天5分钟玩转 Docker 容器技术(99)
    Swarm 如何实现 Failover?- 每天5分钟玩转 Docker 容器技术(98)
    如何实现 Service 伸缩?- 每天5分钟玩转 Docker 容器技术(97)
    运行第一个 Service
  • 原文地址:https://www.cnblogs.com/konglxblog/p/16641490.html
Copyright © 2020-2023  润新知