0
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?

More than 5 years have passed since last update.

JavaScript オブジェクトの参照 注意点

Last updated at Posted at 2019-02-17

JavaScript 配列 参照の注意点

 配列の注意点の備忘録

  • Objectとは

    プリミティブ型(数、文字列、真偽値)以外のものを指す。
    => 配列はObject型

  1. プリミティブ型とObject型の違い

    プリミティブ型は値そのものが代入される。

    例)
    const number = 2  // 2そのものがnumberに入る
    

    Object型はその値が入っている参照(エリア)が代入される。

    例)
    const numbers = [1, 2]    // [1,2]の位置情報がnumbersに入る
    const numbers2 = numbers  // numbers2 : [1, 2]
    numbers[0] = 2            // numbers: [2, 2], numbers2: [2, 2]
    

    元の配列の値を操作すると、numbers2も同じところを指しているため、出力結果が同じ[2,2]になる。

  2. 対処方法

    別の参照を持たせれば、変更の影響は受けない。

    const numbers = [1, 2]
    const numbers2 = numbers.slice()  // コピーを作成
    numbers[0] = 2                    // numbers : [2, 2] , numbers2 : [1, 2]のまま
    

  numbers numbers2の参照が異なるため、numbers2は変更されない。

0
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
0
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?