0
0

More than 3 years have passed since last update.

【JavaScript】スプレッド構文、分割代入を使ったオブジェクトの操作

Last updated at Posted at 2020-05-03

【JavaScript】スプレッド構文、分割代入を使ったオブジェクトの操作

スプレッド構文

①「...」を記述することでオブジェクト内に場所を確保
②①のオブジェクトよりも前に代入するオブジェクトを記述
これによりオブジェクトの中にオブジェクトを追加できる。

例.色情報colorをプロパティに持つcharacterColorオブジェクト。


    const characterColor = {
        color:'red'
    }

キャラクター座標を格納するcharacterPosition に
...characterColorと書き、characterColorの場所を作る。

    const characterPosition  = {

        x: 100,
        y: 200,
        ...characterColor//スプレッド構文

    };
    console.log(characterPosition);//{x: 100, y: 200, color: "red"}

colorプロパティとredが追加されている。

分割代入

xやy,colorを定数として取り出す方法。
たとえば先の手順で作ったcharacterPositionのxは直接参照することができない。

    console.log(x);//ReferenceErrorとなる
    console.log(characterPosition.x);//100

const{} = 定数名
とすることで、xやyを取り出すことができる。


    const {x,y} = characterPosition;
    console.log(x);//100
    console.log(y);//200
0
0
0

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