当前位置:网站首页>Shallow copy, deep copy (implementation mode)
Shallow copy, deep copy (implementation mode)
2022-07-22 15:59:00 【Little Ali】
Both shallow and deep copies are only for reference data types , Shallow copy copies only pointers to an object , Instead of copying the object itself , new
Old objects still share the same memory ; But deep copy creates as like as two peas , The new object does not share memory with the original object ,
Modifying the new object does not change to the original object ;
difference : A shallow copy copies only the first level properties of an object 、 Deep copy can recursively copy the properties of an object ;
Implement shallow copy method
Object.assign Method
var obj = {
a: 1, b: 2 }
var obj1 = Object.assign({
},obj);
boj1.a = 3; console.log(obj.a) // 3
for in Method
// Copy only the shallow copy of the first layer
function simpleCopy(obj1) {
var obj2 = Array.isArray(obj1) ? [] : {
};
for (let i in obj1) {
obj2[i] = obj1[i];
}
return obj2;
}
var obj1 = {
a: 1, b: 2, c: {
d: 3 } }
var obj2 = simpleCopy(obj1);
obj2.a = 3;
obj2.c.d = 4;
alert(obj1.a); // 1
alert(obj2.a); // 3
alert(obj1.c.d); // 4
alert(obj2.c.d); // 4
Implement the deep copy method
Use recursion to copy all hierarchical attributes
function deepClone(obj){
let objClone = Array.isArray(obj)?[]:{
};
if(obj && typeof obj==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
// Judge ojb Is the child element an object , If it is , Recursive replication
if(obj[key]&&typeof obj[key] ==="object"){
objClone[key] = deepClone(obj[key]);
}else{
// If not , Simple replication
objClone[key] = obj[key];
}
}
}
}
return objClone;
}
let a=[1,2,3,4], b=deepClone(a);
a[0]=2;
console.log(a,b);
Use JSON.stringify and JSON.parse Implement deep copy :JSON.stringify Turn the object into a string , Reuse JSON.parse Turn a string into a new object ;
function deepCopy(obj1){
let _obj = JSON.stringify(obj1);
let obj2 = JSON.parse(_obj);
return obj2;
}
var a = [1, [1, 2], 3, 4];
var b = deepCopy(a);
b[1][0] = 2;
alert(a); // 1,1,2,3,4
alert(b); // 2,2,2,3,4
Popular function libraries lodash, There are also offers _.cloneDeep For deep copy ;
var _ = require('lodash');
var obj1 = {
a: 1, b: {
f: {
g: 1 } },
c: [1, 2, 3] };
var obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f); // false
边栏推荐
- 统计,在sql中求每个部门的数据比值
- Redis high availability principle master-slave sentinel cluster
- 浅拷贝,深拷贝(实现方式)
- DOM之12种节点
- What are the common probe set and gallery set
- LeetCode高频题:二叉树的锯齿形(Z字形,之字形)层序遍历
- 微信小程序实现PDF预览功能——pdf.js(含源码解析)
- Ssti Summary and ciscn 2019 South East China] double secret
- Wechat applet realizes PDF preview function - pdf.js (including source code analysis)
- GoldenSection
猜你喜欢
Don't look for it, it's all sorted out for you -- complete collection of SQL statements
Is it true that microservices do not choose databases? How to choose?
SSTI簡單總結和CISCN 2019華東南]Double Secret
C语言输出所有水仙花数
Collagen protease loaded albumin composite nanoparticles / bovine serum albumin coated ceria nano artificial enzyme
Only es works well when checking the log? You didn't use Clickhouse like this
How to improve the efficiency of test case review?
Beijing, Shanghai, Guangzhou, Shenzhen and Hangzhou 30K test question: how to allocate JVM memory model?
QT笔记——自定义的QListWidget
2面字节,被面试官抬着走出去,分享给大家
随机推荐
ROS learning (28) Web GUI
SCM peripheral devices learning strategies, small Bai must see
Check for degenerate boxes
18.redis的持久化机制是什么?各自的优缺点?
Preparation of albumin sorafenib /gd2o3/cus composite albumin nanoparticles /alb-icg-dox albumin nanoparticles coated with ICG & dox
【精讲】Es6 导入 import, 导出 export等多种操作
img.shape[-2:]/len(img.shape[-2:]):GeneralizedRCNN:original_image_sizes中的 torch._assert
3年测试在职经验,面试测试岗连20k都拿不到了吗?有这么坑?
【leetcode】
C language to write 99 multiplication table to realize the output of tables with different triangle shapes
程序环境和预处理
分布式事务,原理简单,写起来全是坑
img.shape[-2:]/len(img.shape[-2:]):GeneralizedRCNN:original_ image_ Torch in sizes_ assert
信息系统项目管理师必背核心考点(四十八)合同类型的选择
socket通信中select函数用法
Bovine serum albumin platinum composite nanomaterials /hsa PC NPs human serum albumin (HSA) coated phthalocyanine nanoparticles
OPENCN学习DAY3
C language question bank part.1
C语言实现通讯录详细教学
理解JS的三座大山