简体   繁体   English

Object.assign 函数是如何工作的?

[英]How does the Object.assign function work?

I would like to clone an object, on order to modify it and not affect the initial object.我想克隆一个对象,以便修改它而不影响初始对象。

let object1 = {
  a: 1,
  b: 2,
  c: 3
};

let object2 = Object.assign(object1);
object2.c = 999;

console.log(object1.c, object2.c);
// expected output: 3 999
// real output: 999 999

I suppose I don't correctly use the "assign" function...我想我没有正确使用“分配”功能......

You need an empty object to assign the properties with Object.assign , because of您需要一个空对象来使用Object.assign分配属性,因为

Object.assign(target, ...sources)
let object2 = Object.assign({}, object1);

 let object1 = { a: 1, b: 2, c: 3 }; let object2 = Object.assign({}, object1); object2.c = 999; console.log(object1.c, object2.c);

Use Object.assign({}, object1) .使用Object.assign({}, object1) the empty object will be cloned, so object1 will be added to the empty object.空对象将被克隆,因此object1将被添加到空对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM