当前位置:网站首页>Use json Stringify() to realize deep copy, be careful, there may be a huge hole

Use json Stringify() to realize deep copy, be careful, there may be a huge hole

2022-07-07 21:58:00 South wind comes late and knows late

When there is a time type in the object ( The time type will be changed to string data )

const obj = {
    date: new Date()
}
console.log(typeof obj.date === 'object') //true
const objCopy = JSON.parse(JSON.stringify(obj));
console.log(obj.date.getTime()) // Normal use 

console.log(typeof objCopy.date) // Output value string  string
console.log(objCopy.date.getTime()) //  Report errors  objCopy.date.getTime is not a function

 We will be surprised to find ,
getTime () It can't be adjusted ???( Is it a little strange )
getYearFull() It can't be adjusted .
 The built-in methods for all time types cannot be adjusted .
 but ,string The built-in method of type is fully adjusted .

Among objects undefined or function Type , They will lose it directly

const obj = {
    undef: undefined,
    fun: () => { console.log(' Creak , ABA, ABA ') }
}
console.log("obj",obj);
const objCopy = JSON.parse(JSON.stringify(obj));
console.log("objCopy",objCopy)
 Then you will find out , Both types of data are gone .
 The return is an empty object 

When there is... In the object NaN、Infinity and -Infinity These three values , Will become null

1.7976931348623157E+10308  Is the maximum number of floating point numbers   Is shown as Infinity
-1.7976931348623157E+10308  Is the minimum lower line of a floating point number   Is shown as -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)

When an object is referenced circularly -- Will report a mistake

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

If you are lucky enough to need to copy such an object

const obj = {
    nan:NaN,
    infinityMax:1.7976931348623157E+10308,
    infinityMin:-1.7976931348623157E+10308,
    undef: undefined,
    fun: () => { console.log(' Creak , ABA, ABA ') },
    date:new Date,
}
 Then you will find out , good heavens , None of them are normal .

Last

 You're still using JSON.stringify() To implement deep copy ?
 If you copy objects with  new Date,undefined, function ,NaN,infinityMax, infinityMin.
 this 6 When planting , You have to be careful , There will be problems 
 If still in use , Be careful .
 Article from link :https://juejin.cn/post/7113829141392130078
原网站

版权声明
本文为[South wind comes late and knows late]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071421261289.html