欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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"}}

 

相关标签: Object.assign js