注册

千万不要用JSON.stringify()去实现深拷贝!有巨坑!!

当对象中有时间类型的元素时候 -----时间类型会被变成字符串类型数据

const obj = {
date:new Date()
}
typeof obj.date === 'object' //true
const objCopy = JSON.parse(JSON.stringify(obj));
typeof objCopy.date === string; //true

然后你就会惊讶的发现,getTime()调不了了,getYearFull()也调不了了。就所有时间类型的内置方法都调不动了。

但,string类型的内置方法全能调了。

当对象中有undefined类型或function类型的数据时 --- undefined和function会直接丢失

const obj = {
undef: undefined,
fun: () => { console.log('叽里呱啦,阿巴阿巴') }
}
console.log(obj,"obj");
const objCopy = JSON.parse(JSON.stringify(obj));
console.log(objCopy,"objCopy")

然后你就会发现,这两种类型的数据都没了。

当对象中有NaN、Infinity和-Infinity这三种值的时候 --- 会变成null

1.7976931348623157E+10308 是浮点数的最大上线 显示为Infinity

-1.7976931348623157E+10308 是浮点数的最小下线 显示为-Infinity

const obj = {
nan:NaN,
infinityMax:1.7976931348623157E+10308,
infinityMin:-1.7976931348623157E+10308,
}
console.log(obj, "obj");
const objCopy = JSON.parse(JSON.stringify(obj));
console.log(objCopy,"objCopy")

当对象循环引用的时候 --会报错

const obj = {
objChild:null
}
obj.objChild = obj;
const objCopy = JSON.parse(JSON.stringify(obj));
console.log(objCopy,"objCopy")

假如你有幸需要拷贝这么一个对象 ↓

const obj = {
nan:NaN,
infinityMax:1.7976931348623157E+10308,
infinityMin:-1.7976931348623157E+10308,
undef: undefined,
fun: () => { console.log('叽里呱啦,阿巴阿巴') },
date:new Date,
}

然后你就会发现,好家伙,没一个正常的。

image.png

你还在使用JSON.stringify()来实现深拷贝吗?

如果还在使用的话,小心了。作者推荐以后深拷贝使用递归的方式进行深拷贝。

原文:https://juejin.cn/post/7113829141392130078

0 个评论

要回复文章请先登录注册