/*
---------------------------------------------------------------------
## 深拷贝 => 复制体改变, 原体不改变 => 只保存在栈内存上
## 包含的数据类型 : Number String Boolean NULL undefined Symbol
let a = 100;
let aCopy = a;
aCopy = 200;
console.log(a);
打印结果 :
100
console.log(aCopy);
打印结果 :
200
======================================
let ccc = { name: "zhansan", age: 11 }
let b = ccc.name;
b = "zhaoliu";
let k = ccc.age;
k = 100;
console.log(ccc);
打印结果:
{
age: 11,
name: "张三",
}
======================================
let newArr = [{ name: "zhangsan", age: 18 }, { name: "lisi", age: 20 }]
let y = newArr[0].name;
y = "wangwu";
console.log(newArr);
打印结果:
[
{
age: 18,
name: "zhangsan",
},
{
age: 20,
name: "lisi",
}
]
---------------------------------------------------------------------
## 浅拷贝 => 复制体改变, 原体改变 => 保存在堆内存,通过地址引用
## 包含的数据类型 : Function Array Object Date Math RegExp
let newObj = { name: "张三", age: 18 };
let newObjCopy = newObj;
newObjCopy.name = "李四";
newObjCopy.age = 26;
console.log(newObj);
打印结果 :
{
age:26,
name:"李四",
}
console.log(newObjCopy);
打印结果 :
{
age:26,
name:"李四",
}
======================================
let newArr = [{ name: "zhangsan", age: 18 }, { name: "lisi", age: 20 }]
let y = newArr[0];
y.name = "wangwu";
console.log(newArr);
打印结果:
[
{
age: 18,
name: "wangwu",
},
{
age: 20,
name: "lisi",
}
]
---------------------------------------------------------------------
## 浅拷贝 变成 深拷贝的方法
方法1 : JSON.parse(JSON.stringify())
## 缺陷:
1. 函数无法拷贝
2. 正则无法拷贝
3. undefuned 无法拷贝
## 优点:
1. 二级以后的也会被拷贝
let newObj = { name: "张三", age: 18 };
let newObjCopy2 = JSON.parse(JSON.stringify(newObj))
newObjCopy2.name = "王五";
newObjCopy2.age = 30;
console.log(newObj);
打印结果 :
{
age:18,
name:"张三",
}
console.log(newObjCopy2);
打印结果 :
{
age:30,
name:"王五",
}
========================================
方法2: Object.assign(target, source)
## 缺陷:
1. 二级以后的不会被拷贝
## 优点:
1. 函数可以拷贝
2. 正则可以拷贝
3. undefuned 可以拷贝
let newObj = {
name: "张三",
age: 18,
say() {
console.log("hello world !");
},
reg: /d/,
data: undefined,
};
let newObjCopy2 = {};
Object.assign(newObjCopy2, newObj)
newObjCopy2.name = "王五";
newObjCopy2.age = 30;
console.log(newObj);
打印结果:
{
name: "张三",
age: 18,
say() {
console.log("hello world !");
},
reg: /d/,
data: undefined,
}
---------------------------------------------------------------------
*/
js 深拷贝和浅拷贝
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 壹 ❀ 引 如何区分深拷贝与浅拷贝,简单点来说,就是假设B复制了A,当修改A时,看B是否会发生变化,如果B也跟着变...