1,前景提要:
(1)数字在被复制后,再修改时,不会改变原值:
var a=5;
var b=a;
b=7;
console.log(a); // a不变
(2)对象在被复制后,再修改时,会改变原值:
var a = { name: "hello"};
var b = a;
b.name="hi";
console.log(a); // a.name = "hi"
2,浅拷贝:拷贝一层对象。深拷贝:拷贝多层对象
3,方法:
(1)Object.assign( ):
var a = { name : "hello" } ;
var b = Object.assign({ }, a);
b.name = "hi";
console.log( a ); // a.name不变
ps,适合浅拷贝
(2)扩展运算符:
var a = { name : "hello" } ;
var b = {...a};
b.name = "hi";
console.log( a ); // a.name不变
ps,适合浅拷贝
(3)JSON.parse( ) + JSON.stringify:
var a = {
info: {
name:"hello"
}
}
var b = JSON.parse(JSON.stringify(a));
b.info.name = "hi";
console.log(a); // a.info.name不变
ps,适合深拷贝
(4)for in & 递归:
略,详情参考:https://www.bilibili.com/video/BV1LK4y1s7ZW?p=6