千萬不要用JSON.stringify()去實(shí)現(xiàn)深拷貝!有巨坑?。?/font>
1.當(dāng)對(duì)象中有時(shí)間類型的元素時(shí)候
時(shí)間類型會(huì)被變成字符串類型數(shù)據(jù)
const obj = {
date:new Date()
}
typeof obj.date === 'object' //true
const objCopy = JSON.parse(JSON.stringify(obj));
typeof objCopy.date === string; //true
然后你就會(huì)驚訝的發(fā)現(xiàn),getTime()調(diào)不了了,getYearFull()也調(diào)不了了。就所有時(shí)間類型的內(nèi)置方法都調(diào)不動(dòng)了。
但,string 類型的內(nèi)置方法全能調(diào)了。
2.當(dāng)對(duì)象中有 undefined 類型或 function 類型的數(shù)據(jù)時(shí)
undefined 和 function 會(huì)直接丟失
const obj = {
undef: undefined,
fun: () => { console.log('嘰里呱啦,阿巴阿巴') }
}
console.log(obj,"obj");
const objCopy = JSON.parse(JSON.stringify(obj));
console.log(objCopy,"objCopy")
然后你就會(huì)發(fā)現(xiàn),這兩種類型的數(shù)據(jù)都沒了。
3.當(dāng)對(duì)象中有 NaN、Infinity 和-Infinity 這三種值的時(shí)候
會(huì)變成 null
「1.7976931348623157E+10308 是浮點(diǎn)數(shù)的最大上限 顯示為 Infinity」
「-1.7976931348623157E+10308 是浮點(diǎn)數(shù)的最小下限 顯示為-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")
4.當(dāng)對(duì)象循環(huán)引用的時(shí)候
會(huì)報(bào)錯(cuò)
const obj = {
objChild:null
}
obj.objChild = obj;
const objCopy = JSON.parse(JSON.stringify(obj));
console.log(objCopy,"objCopy")
假如你有幸需要拷貝這么一個(gè)對(duì)象 ↓
const obj = {
nan:NaN,
infinityMax:1.7976931348623157E+10308,
infinityMin:-1.7976931348623157E+10308,
undef: undefined,
fun: () => { console.log('嘰里呱啦,阿巴阿巴') },
date:new Date,
}
然后你就會(huì)發(fā)現(xiàn),好家伙,沒一個(gè)正常的。
你還在使用JSON.stringify()來實(shí)現(xiàn)深拷貝嗎?
總結(jié)
對(duì)象中有時(shí)間類型的時(shí)候,序列化之后會(huì)變成字符串類型。
對(duì)象中有undefined和Function類型數(shù)據(jù)的時(shí)候,序列化之后會(huì)直接丟失。
對(duì)象中有NaN、Infinity和-Infinity的時(shí)候,序列化之后會(huì)顯示 null。
對(duì)象循環(huán)引用的時(shí)候,會(huì)直接報(bào)錯(cuò)。
最后,深拷貝建議使用遞歸,安全方便。
原文連接:https://juejin.cn/post/7113829141392130078 作者:工邊頁(yè)字
作者:工邊頁(yè)字
歡迎關(guān)注微信公眾號(hào) :前端開發(fā)愛好者
添加好友備注【進(jìn)階學(xué)習(xí)】拉你進(jìn)技術(shù)交流群