使用JSON.stringify()实现深拷贝,小心哪些潜在巨坑?

2026-04-11 07:410阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计562个文字,预计阅读时间需要3分钟。

使用JSON.stringify()实现深拷贝,小心哪些潜在巨坑?

javascript对象中包含时间类型的日期(时间类型会被转换为字符串类型)+ const obj={ date: new Date() }; console.log(typeof obj.date==='object'); // true const objCopy=JSON.parse(JSON.stringify(obj)); console.log(objCopy.date.getTime()); // 输出时间戳

使用JSON.stringify()实现深拷贝,小心哪些潜在巨坑?

对象中有时间类型的时候(时间类型会被变成字符串类型数据)

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类型的内置方法全能调了。

阅读全文

本文共计562个文字,预计阅读时间需要3分钟。

使用JSON.stringify()实现深拷贝,小心哪些潜在巨坑?

javascript对象中包含时间类型的日期(时间类型会被转换为字符串类型)+ const obj={ date: new Date() }; console.log(typeof obj.date==='object'); // true const objCopy=JSON.parse(JSON.stringify(obj)); console.log(objCopy.date.getTime()); // 输出时间戳

使用JSON.stringify()实现深拷贝,小心哪些潜在巨坑?

对象中有时间类型的时候(时间类型会被变成字符串类型数据)

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类型的内置方法全能调了。

阅读全文