1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript の参照によるコピーとプリミティブ型

Posted at

JavaScript の参照によるコピー

概要

JavaScript で変数に値を代入する際、データ型によってコピー方式が異なります。

プリミティブ型

プリミティブ型は値そのものがコピーされます。

  • 型: stringnumberbooleanundefinednullsymbolbigint
let a = 10;
let b = a;  // 値のコピー
b = 20;
console.log(a);  // 10 (変更されない)
console.log(b);  // 20

参照型

参照型はメモリアドレスがコピーされ、同じオブジェクトを指します。

  • 型: objectarrayfunction など
let person1 = { name: 'John', age: 30 };
let person2 = person1;  // 参照のコピー
person2.age = 35;
console.log(person1.age);  // 35 (一緒に変更される)

コピー方法

浅いコピー(Shallow Copy)

最上位のプロパティのみをコピーし、ネストされたオブジェクトは参照を共有します。

let original = {
  name: 'Alice',
  hobbies: ['reading', 'biking']
};

let copy = { ...original };  // スプレッド演算子
copy.name = 'Bob';
copy.hobbies.push('swimming');

console.log(original.name);     // Alice (変更されない)
console.log(original.hobbies);  // ['reading', 'biking', 'swimming'] (変更される)

深いコピー(Deep Copy)

ネストされたすべてのオブジェクトまで完全にコピーします。

let original = {
  name: 'Alice',
  hobbies: ['reading', 'biking']
};

// JSON方法
let copy = JSON.parse(JSON.stringify(original));

// または lodash ライブラリ
const _ = require('lodash');
let copy = _.cloneDeep(original);

copy.hobbies.push('swimming');
console.log(original.hobbies);  // ['reading', 'biking'] (変更されない)

まとめ

  • プリミティブ型: 値のコピーで独立的
  • 参照型: アドレスのコピーで同じオブジェクトを参照
  • 浅いコピー: 最上位のみコピー
  • 深いコピー: すべてのレベルを完全にコピー
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?