当前位置:网站首页>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)

边栏推荐
- LeetCode 2347. 最好的扑克手牌
- Realize OCR language recognition demo (II) - display and interaction of pictures and recognition content
- Niuke net question brushing training (III)
- Cap principle of [distributed development]
- C语言·指针
- VLAN实验
- Interpretation of new features | the restriction of MySQL 8.0 on gtid is lifted
- Software test interview question: what are the performance test indicators?
- Can ordinary equipment access TSN time sensitive network?
- 自定义事件
猜你喜欢
随机推荐
实现OCR语言识别Demo(二)- 图片及识别内容的展现和交互
华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
docker 本地搭建mysql主从
小散量化炒股记|量化系统中数据是源头,教你搭建一款普适的数据源框架
企业运维实践-使用Aliyun容器镜像服务对海外gcr、quay仓库镜像进行镜像拉取构建
26.抽象化和模板思想
[add pictures to dice roller app]
Learn how Baidu PaddlePaddle easydl realizes automatic animal recognition in aquarium
Baidu PaddlePaddle easydl: when AI enters the factory, "small bearing" can also turn "big industry"
Thoroughly understand kubernetes scheduling framework and plug-ins
Login function implementation
Can ordinary equipment access TSN time sensitive network?
Software test interview question: how to prepare test data? How to prevent data pollution?
登录功能实现
"Wei Lai Cup" 2022 Niuke summer multi school training camp 3 supplementary problem solution (a, C, J)
了解Shader
qt 设置图标
HCIP第十五天
Unity shader introduction Essentials - basic texture
数仓搭建——DWS层









