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?

【JSノート】プリミティブ型とオブジェクト型、浅いコピーと深いコピー

Last updated at Posted at 2025-01-27

プリミティブ型とオブジェクト型

プリミティブ型

  • 数値 (number)、文字列 (string)、真偽値 (boolean)、undefinednullsymbolbigint などが含まれる
  • 値そのものがコピーされるため、変更が元の値に影響しない

例:

let a = 10; // プリミティブ型(数値)
let b = a;  // a の値をコピー

b = 20; // b を変更しても a に影響しない
console.log(a); // 10
console.log(b); // 20

オブジェクト型

  • 配列 (Array)、オブジェクト (Object)、関数 (Function) などが含まれる
  • 参照がコピーされるため、変更が元の値に影響する

例:

let obj1 = { x: 10 }; // オブジェクト型
let obj2 = obj1;      // obj1 の参照をコピー

obj2.x = 20; // obj2 を変更すると obj1 にも影響する
console.log(obj1.x); // 20
console.log(obj2.x); // 20

浅いコピーと深いコピー

浅いコピー

  • 一階層目のプロパティだけをコピーする。ネスト*されたオブジェクトや配列は参照がコピーされる

例:

let original = { a: 1, b: { c: 2 } };
let shallowCopy = { ...original }; // 浅いコピー

shallowCopy.b.c = 3; // ネスト*されたオブジェクトの変更が元のオブジェクトに影響
console.log(original.b.c); // 3

深いコピー

  • ネスト*されたオブジェクトや配列もすべて再帰的にコピーする。元のオブジェクトと完全に独立する

例:

let original = { a: 1, b: { c: 2 } };

// 深いコピー (JSON を使用する簡易方法)
let deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.b.c = 3; // 深いコピーの変更は元のオブジェクトに影響しない
console.log(original.b.c); // 2

浅いコピーと深いコピーの方法

  • 浅いコピー
    • Object.assign() またはスプレッド構文 ({ ...object })
  • 深いコピー
    • ネスト*が浅い場合は JSON.parse(JSON.stringify(object))
    • ネスト*が深い場合や非標準オブジェクトを含む場合は、再帰関数やライブラリ(例: Lodash の cloneDeep)を使用する

例:

// 深いコピー: 再帰関数の例
function deepClone(obj) {
  if (obj === null || typeof obj !== "object") return obj;

  let clone = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    clone[key] = deepClone(obj[key]);
  }
  return clone;
}

let original = { a: 1, b: { c: 2 } };
let clone = deepClone(original);

clone.b.c = 3;
console.log(original.b.c); // 2

*ネスト(英: nesting):プログラミングにおいて 「入れ子」 のようにデータや構造が他のデータや構造の中に含まれることを指す。

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?