当前位置:网站首页>js 哪些情况不能用 JSON.parse 、JSON.stringify深拷贝及一个更好的深拷贝方法
js 哪些情况不能用 JSON.parse 、JSON.stringify深拷贝及一个更好的深拷贝方法
2022-07-27 23:54:00 【不能懒鸭】
先说一个js概念 —>
对象序列化:是将对象的状态变成字符串(JSON.stringify),也可将字符串还原为对象(JSON.parse)。
我们通常使用这种方法对 拷贝一个js对象,但是当某些情况下,会有问题,比如下面几种情况。
对象中有NaN、Infinity和-Infinity的时候,序列化之后会变成null。
对象中有undefined和Function类型数据的时候,序列化之后会直接丢失。
对象中有时间类型的时候,序列化之后会变成字符串类型。
对象循环引用的时候,序列化之后会直接报错。
const obj = {
nan:NaN,
infinityMax:1.7976931348623157E+10308,
infinityMin:-1.7976931348623157E+10308,
undef: undefined,
fun: () => {
console.log(123) },
date:new Date,
name:'张三',
wife:obj.name
}
项目中推荐使用递归的方法封装一个工具函数
//utils.js
//...
const deepCopy= (obj = {
}) => {
//变量先置空
let newobj = null;
//判断是否需要继续进行递归
if (typeof (obj) == 'object' && obj !== null) {
newobj = obj instanceof Array ? [] : {
};
//进行下一层递归克隆
for (var i in obj) {
newobj[i] = deepCopy(obj[i])
}
//如果不是对象直接赋值
} else newobj = obj;
console.log(newobj)
return newobj;
}
使用:
let person= {
name:'zhangsan',
age:26,
wife:{
sheName:'xiaohua',
sheAge:25
}
}
let newPerson= deepCopy(person)

边栏推荐
- String
- Modify the request path using the streaming API of gateway
- C # learning notes ----- C # connect to MySQL database
- LeetCode 2351. 第一个出现两次的字母
- The understanding of domain adaptation in transfer learning and the introduction of three technologies
- EEG多元模式分析预测慈善捐赠行为
- Let's move forward together, the 10th anniversary of Google play!
- Oracle Rac 集群文件目录迁移
- 【向 Dice Roller 应用添加图片】
- 画刷和画笔
猜你喜欢
随机推荐
HCIP第十五天
华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
Linux安装mysql8.0.29详细教程
Redis 5 种基本数据结构
IIC读写EEFPROM
Discussion on PHP using some functions bypass WAF
Oracle Rac 集群文件目录迁移
For newly installed PIP3, use no module named 'LSB_ Release 'problem
使用Gateway的流式api修改请求路径
负载均衡SLB
【样式集合1】tab 栏
C # learning notes ----- C # connect to MySQL database
Blizzard Diablo 4 ps5 / PS4 beta added to Playstation database
Oracle RAC cluster file directory migration
软件测试面试题:think_time的作用是什么?
Recursion related exercises
画刷和画笔
IIC read / write eefprom
3000 words and 11 pictures hard core popular science: what is edge computing? What are the connections and differences with cloud computing?
Can anime characters become "real people"? Paddegan helps you find the TA of "tear man"








