美文网首页
JSON.stringify深拷贝的缺点

JSON.stringify深拷贝的缺点

作者: 景元合 | 来源:发表于2020-03-09 17:59 被阅读0次

1、如果obj里面有时间对象,则JSON.stringify后再JSON.parse的结果,时间将只是字符串的形式,而不是对象的形式

const obj={
    date:new Date()
}
console.log(typeof JSON.parse(JSON.stringify(obj)).date)
//string

2、如果obj里面有RegExp,则打印出来是空对象

const obj={
    date: new RegExp('\\w+'),
    name:'111'
}
console.log(obj.date)
console.log(JSON.parse(JSON.stringify(obj)).date)
///\w+/
//{}

3、如果对象中有函数或者undefined,则会直接被丢掉

const obj={
    date:function(){
        console.log(1)
    },
    name:undefined,
}
console.log(obj)
console.log(JSON.parse(JSON.stringify(obj)))
//{ date: [Function: date], name: undefined }
//{}

4、如果json里有对象是由构造函数生成的,则会丢掉对象的constructon

function Person(name){
    this.name=name
}
let li=new Person('lili')
const obj={
    name:li
}
console.log(obj.name.__proto__.constructor)
console.log(JSON.parse(JSON.stringify(obj)).name.__proto__.constructor)
//[Function: Person]
//[Function: Object]

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

let obj={
    age:18
}
obj.obj=obj;
console.log(obj)
console.log(JSON.parse(JSON.stringify(obj)))
{ age: 18, obj: [Circular] }
C:\Users\ADMINI~1\AppData\Local\Temp\tempCodeRunnerFile.javascript:6
console.log(JSON.parse(JSON.stringify(obj)))
                            ^
TypeError: Converting circular structure to JSON

6、如果对象中存在NAN,则序列化后会变成null

let obj={
    age:NaN
}
console.log(obj)
console.log(JSON.parse(JSON.stringify(obj)))
{ age: NaN }
{ age: null }

相关文章

网友评论

      本文标题:JSON.stringify深拷贝的缺点

      本文链接:https://www.haomeiwen.com/subject/llgpdhtx.html