はじめに
JavaScriptの便利な分割代入をまとめてみました。
ここでは例として左辺は変数を使用していますが、変数以外でも可能です。
基本
左辺の変数名は自由に設定でき、マッチする右辺の配列の要素により初期化されます。
const animals = ["dog", "cat", "monkey"]
const [first, second, third] = animals
// first ... dog
// second ... cat
// third ... monkey
オブジェクトの分割代入は左辺にプロパティ名を指定します。
const monkey = {name: "George", gender: "boy"}
const { name, gender } = monkey
// name ... "George"
// gender ... "boy"
左辺の変数にマッチする要素が右辺に存在しない場合は、undefinde
になります。
const animals = ["dog", "cat"]
const [first, second, third] = animals
// first ... dog
// second ... cat
// third ... undefined
const monkey = {name: "George", gender: "boy"}
const { name, age } = monkey
// name ... "George"
// age ... undefinde
不必要な値を無視
不必要な値が存在する場合は無視することができます。
const animals = ["dog", "cat", "monkey"]
const [first, second] = animals
// first ... dog
// second ... cat
const animals = ["dog", "cat", "monkey"]
const [first, , third] = animals
// first ... dog
// third ... monkey
ネストされたオブジェクト
ネストされたオブジェクトから分割代入を行う場合は以下のように左辺を期待する要素にマッチするよう記述します。
const monkey = {name: "George", gender: "boy", birthday: {year: 1995, mounth: 4, day: 1}}
const { birthday: {mounth, day} } = monkey
// mounth ... 4
// day ... 1
デフォルト値
マッチする要素がない場合などで左辺の値が undefinde になる際に使用するデフォルトの値を設定できます。
const animals = ["dog", "cat"]
const [first, second, third = "wallaby"] = animals
// first ... dog
// second ... cat
// third ... "wallaby"
const monkey = {name: "George", gender: "boy"}
const { name, age = 3 } = monkey
// name ... "George"
// age ... 3
オブジェクトの場合は以下の方法で指定もできます。
const monkey = {name: "George", gender: "boy"}
const { nickname = name } = monkey
// nikcname ... "George"
rest宣言
分割代入の指定として その他の要素
という指定ができます。
指定方法は変数名の頭に ...
を付けるだけです。
const animals = ["dog", "cat", "monkey"]
const [first, ...others] = animals
// first ... dog
// others ... ["cat", "monkey"]
const monkey = {name: "George", gender: "boy", birthday: {year: 1995, mounth: 4, day: 1}}
const { birthday, ...others } = monkey
// birthday ... {year: 1995, mounth: 4, day: 1}
// others ... {name: "George", gender: "boy"}
さいごに
最後まで読んでいただき、ありがとうございました。