简体   繁体   中英

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(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) . the empty object will be cloned, so object1 will be added to the empty object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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