Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
25
Help us understand the problem. What is going on with this article?
@tomson

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

More than 1 year has passed since last update.

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の値を変更しても影響を受けていないことが分かる。それぞれ記法としては現場でよく使われるので覚えておくと便利である。

25
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
tomson

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
25
Help us understand the problem. What is going on with this article?