当前位置:网站首页>JS what situations can't use json Parse, json.stringify deep copy and a better deep copy method
JS what situations can't use json Parse, json.stringify deep copy and a better deep copy method
2022-07-28 01:57:00 【No lazy duck】
Let's start with one js Concept —>
Object serialization : Is to change the state of an object into a string (JSON.stringify), You can also restore strings to objects (JSON.parse).
We usually use this method to Copy one js object , But in some cases , There will be problems. , For example, in the following cases .
Among objects NaN、Infinity and -Infinity When , After serialization, it will become null.
Among objects undefined and Function When it comes to type data , After serialization, it will be lost directly .
When there is a time type in the object , After serialization, it becomes a string type .
When an object is referenced circularly , Errors will be reported directly after serialization .
const obj = {
nan:NaN,
infinityMax:1.7976931348623157E+10308,
infinityMin:-1.7976931348623157E+10308,
undef: undefined,
fun: () => {
console.log(123) },
date:new Date,
name:' Zhang San ',
wife:obj.name
}
It is recommended to use recursive method to encapsulate a tool function in the project
//utils.js
//...
const deepCopy= (obj = {
}) => {
// Empty variable first
let newobj = null;
// Determine whether recursion needs to continue
if (typeof (obj) == 'object' && obj !== null) {
newobj = obj instanceof Array ? [] : {
};
// Perform the next level of recursive cloning
for (var i in obj) {
newobj[i] = deepCopy(obj[i])
}
// If the object is not directly assigned
} else newobj = obj;
console.log(newobj)
return newobj;
}
Use :
let person= {
name:'zhangsan',
age:26,
wife:{
sheName:'xiaohua',
sheAge:25
}
}
let newPerson= deepCopy(person)

边栏推荐
猜你喜欢
随机推荐
What is method and methodology: understand the underlying logic of self-improvement
DeviceXPlorer OPC Server支持哪些设备?本文已列举出来了
Simplicity for beauty - programming ideas
数据安全与隐私计算峰会-可证明安全:学习
企业运维实践-使用Aliyun容器镜像服务对海外gcr、quay仓库镜像进行镜像拉取构建
了解Shader
集合/容器
HRD 1. a simple and reliable HRD detection method
【面试:并发篇28:volatile】有序性
【向 Dice Roller 应用添加图片】
白质脑功能网络图论分析:抑郁症分类和预测的神经标记
周报、月报有多折磨人?万能报表模板建议收藏!(附模板)
N32L43x Flash读\写\擦除操作总结
处理数据 给数据换名字
likeshop外卖点餐系统【100%开源无加密】
在生产型企业中,MES系统有哪些重要应用
HCIP第十五天
HCIP第十二天笔记
GBase 8c 事务ID和快照(四)
Enterprise operation and maintenance practice - using aliyun container image service to pull and build images of overseas GCR and quay warehouses









