对象中有时间类型的时候(时间类型会被变成字符串类型数据)
const obj = { date: new Date() } console.log(typeof obj.date === 'object') //true const objCopy = JSON.parse(JSON.stringify(obj)); console.log(obj.date.getTime()) //正常使用 console.log(typeof objCopy.date) //输出的值字符串 string console.log(objCopy.date.getTime()) // 报错 objCopy.date.getTime is not a function 我们就会惊讶的发现, getTime ()调不了了???(是不是有点奇怪) getYearFull()也调不了了。 就所有时间类型的内置方法都调不动了。 但,string类型的内置方法全能调了。
对象中有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, } 然后你就会发现,好家伙,没一个正常的。
最后
你还在使用JSON.stringify()来实现深拷贝吗? 如果你拷贝的对象中有 new Date,undefined,函数,NaN,infinityMax, infinityMin。 这6种的时候,你就要小心了,就会出现问题 如果还在使用的话,小心了。 文章来自链接:https://juejin.cn/post/7113829141392130078