0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでObjectのDeep copy (←嘘)

Last updated at Posted at 2016-12-18

JavaScriptでObjectのDeep copyする時は
Object.assignを使う(←嘘)

IE11とか、変な条件でなければだいたい使えるみたい


と思ったら、指摘を頂いて確認してみたところ、
一階層目しか値コピーできていない事がわかった。

この場合はいい

let a = {x: 1, y: 2};
let b = Object.assign({}, a);

b.y = 3;

console.log(a); // {x: 1, y: 2}
console.log(b); // {x: 1, y: 3}

この場合はだめ

let a = {x: 1, y: {Y: 2}};
let b = Object.assign({}, a);

b.y.Y = 3;

console.log(a); // {x: 1, y: {Y: 3}}
console.log(b); // {x: 1, y: {Y: 3}}
0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?