使用JSON.stringify()深拷贝时,注意潜在巨大风险,如何避免?
- 内容介绍
- 文章标签
- 相关推荐
本文共计574个文字,预计阅读时间需要3分钟。
在对象中存在时间类型的属性(时间类型会被转换为字符串类型数据)。
const obj={ date: new Date() };console.log(typeof obj.date==='object') // trueconst objCopy=JSON.parse(JSON.stringify(obj));console.log(obj.date.getTime()) // 1640995200000
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()也调不了了。
就所有时间类型的内置方法都调不动了。
本文共计574个文字,预计阅读时间需要3分钟。
在对象中存在时间类型的属性(时间类型会被转换为字符串类型数据)。
const obj={ date: new Date() };console.log(typeof obj.date==='object') // trueconst objCopy=JSON.parse(JSON.stringify(obj));console.log(obj.date.getTime()) // 1640995200000
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()也调不了了。
就所有时间类型的内置方法都调不动了。

