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】配列を代入する際の注意点

Last updated at Posted at 2025-10-05

JavaScriptでは、以下のように配列を代入すると:

const array1 = [1, 2, 3, 4];
const array2 = array1;

見た目上は array1 を array2 に代入しているように見えますが、
実際には「値のコピー」ではなく「参照のコピー」になります。array1 と array2 は
同じ配列オブジェクトを参照しています。どちらかの配列を変更すると、もう一方にも影響が出ます。

スクリーンショット 2025-10-05 21.36.06.png

正しく配列を代入する方法

これらの方法を使うと、新しく独立した配列が作成されます。

スプレッド構文

const array2 = [...array1];

Sliceメソッド

const array2 = array1.slice();

スクリーンショット 2025-10-05 21.35.30.png

1
0
3

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?