Object.assign 是浅拷贝还是深拷贝?
程序员文章站
2022-03-21 22:18:10
...
首先,我们要说的是Object.assign的基本用法:
Object.assign(目标,数据1,数据2....);
示例:
//示例1
let obj = {a:1}
let newObj = Object.assign({},obj);
console.log(newObj) //{a: 1}
//示例2
let obj1 = {name:"zhangsan"};
let obj2 = {age:18};
let obj3 = Object.assign({},obj1,obj2);
console.log(obj3) //{name: "zhangsan", age: 18}
关于Object.assign是浅拷贝还是深拷贝的问题:
答:第一级属性深拷贝,从第二级属性开始就是浅拷贝。
示例:
//示例1 一层深拷贝
let obj = {a:1}
let newObj = Object.assign({},obj);
console.log(newObj); //{a: 1}
newObj.a=2;
console.log(obj); //{a:1}
console.log(newObj); //{a: 2}
//示例2 二层浅拷贝
let obj = {a:1,b:{name:"zhangsan"}}
let newObj = Object.assign({},obj);
console.log(newObj); //{a:1,b:{name:"zhangsan"}}
newObj.b.name="lisi";
console.log(obj); //{a:1,b:{name:"lisi"}}
console.log(newObj); //{a:1,b:{name:"lisi"}}
下一篇: 插入排序