`
yuyongkun4519
  • 浏览: 43097 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

ES6 能否使用Object.assign实现深浅拷贝

 
阅读更多

 

Object.assign方法是浅拷贝还是深拷贝?

1,普通变量

let obj={name:"zhangsan",colors:["red", "green", "blue"]};
let obj2=Object.assign({},obj);
obj2.name='wang';
console.log(obj2);//name wang colors:["red", "green", "blue"]
console.log(obj);//name zhangsan colors:["red", "green", "blue"]

 2,引用变量

let obj={name:"zhangsan",colors:["red", "green", "blue"]};
let obj2=Object.assign({},obj);
obj2.colors[0]='orange';
console.log(obj2);//name zhangsan colors:["orange", "green", "blue"]
console.log(obj);//name zhangsan colors:["orange", "green", "blue"]

 所以Object.assign对于含有引用类型值的对象无法深拷贝。

 

3,如果参数是数组

普通数组

let colors=['red','green','blue'];
let colors2=Object.assign([],colors);
colors2[0]="orange";
console.log(colors2);//['orange','green','blue']
console.log(colors);//['red','green','blue']

含有引用类型的值的数组

let colors=['red','green','blue',['football','basketball','volleyball']];
let colors2=Object.assign([],colors);
colors2[3][0]="ping-pang";
console.log(colors2);//['red','green','blue',['ping-pang','basketball','volleyball']]
console.log(colors);//['red','green','blue',['ping-pang','basketball','volleyball']]

  和上面一样,如果一维数组里面有引用类型的值,则无法深拷贝。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics