目录
三、NaN、Infinity 和 -Infinity 被序列化为 null
四、只能序列化对象可枚举的 自有属性,如果通过构造函数new出来的实例,则会丢失constructor构造函数
在项目中很多人为求简单、方便在进行数据的深拷贝时会采用JSON.parse(JSON.stringify(...))的方式,殊不知,这两个组合的深克隆方式存在很多弊端,要慎用!
当被序列化的数据中有Function 或 undefined 时,序列化后,Function 和 undefined 会丢失
- <script>
- let obj = {
- name: 'lili',
- age: 13,
- address: undefined,
- sayHello: function() {
- console.log(`my name is ${this.name}`);
- }
- }
- let copyObj = JSON.parse(JSON.stringify(obj));
- console.log(copyObj);
- </script>

- <script>
- let obj = {
- time1: new Date(),
- time2: new Date(1656313196128)
- }
- console.log(obj);
- let copyObj = JSON.parse(JSON.stringify(obj))
- console.log(copyObj);
- </script>

- <script>
- let obj = {
- notANumber: NaN,
- positiveNum: Infinity,
- minusNum: -Infinity
- }
- console.log(obj);
- let copyObj = JSON.parse(JSON.stringify(obj))
- console.log(copyObj);
- </script>

- <script>
- function Student(name) {
- this.name = name
- }
- let lili = new Student('lili')
- let Student1 = {
- name: lili,
- hobby: '羽毛球'
- }
- console.log(Student1);
- let copyStudent1 = JSON.parse(JSON.stringify(Student1))
- console.log(copyStudent1);
- </script>

- <script>
- let obj = {
- regularObj: new RegExp('/^1[3456789]\d{9}$/'),
- errorObj: new Error('出错了!')
- }
- console.log(obj);
- let copyObj = JSON.parse(JSON.stringify(obj))
- console.log(copyObj);
- </script>

- <script>
- let obj = {
- name: 'lili'
- }
- obj.details = obj
- console.log(obj);
- let copyObj = JSON.parse(JSON.stringify(obj))
- console.log(copyObj);
- </script>

lodash里除了深克隆的方法外,还有很多实用的方法,详情可查看官方文档: