JS浅拷贝、深拷贝

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

上一篇:(转)js函数前加分号和感叹号是什么意思?有什么用?


下一篇:MySQL常见约束(主键,外键,默认,非空,检查,唯一)