LoginSignup
48
31

More than 5 years have passed since last update.

Javascript配列のコピー方法(Deep/Shallow/代入)備忘録

Last updated at Posted at 2019-03-03

Javascriptの配列をコピーする時には、単に代入する、第一階層の値だけコピーする(Shallow Copy)、全てをコピーする(Deep Copy)の3通りのコピー方法がある。

例を見ると次の通り

const array = [1,1,1,1,{a: 1}];
const array2 = array;  // 代入
const array3 = [...array]; // spread演算子による展開代入 (Shallow Copy)
const array4 = array.concat(); // concatによるShallow Copy
const array5 = JSON.parse(JSON.stringify(array)); // Serialize/DeserializeによるDeep Copy
array[0] = 2;
array[4].a = 2;
console.log(array);   // [ 2, 1, 1, 1, { "a": 2 } ]
console.log(array2);  // [ 2, 1, 1, 1, { "a": 2 } ]
console.log(array3);  // [ 1, 1, 1, 1, { "a": 2 } ]
console.log(array4);  // [ 1, 1, 1, 1, { "a": 2 } ]
console.log(array5);  // [ 1, 1, 1, 1, { "a": 1 } ]

Shallow CopyではObjectではない要素が、またDeep Copyでは全ての要素がarrayと異なる参照先を持っており、arrayの値を変更しても影響を受けていないことが分かる。それぞれ記法としては現場でよく使われるので覚えておくと便利である。

48
31
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
48
31