2
0

【JavaScript】分割代入

Posted at

O'reillyのJavaScript 第7版を読んで、
今まであまり使用していない技術がいろいろ載っていました。

今回はその中の分割代入についてまとめてみました。

分割代入とは

そもそも分割代入とは何でしょうか。

MDN web docsには次のように記載されています。

分割代入 (Destructuring assignment) 構文は、配列から値を取り出して、あるいはオブジェクトからプロパティを取り出して別個の変数に代入することを可能にする JavaScript の式です。

-- 分割代入 - JavaScript - MDN Web Docs - Mozilla

使い方

説明文だけでは分かりづらいので、使い方の例を見てみましょう。

配列の代入

let [x, y] = [1, 2];

console.log(x); // 1
console.log(y); // 2

左辺と右辺の要素数を揃える必要はありません。

let [x, y] = [1];

console.log(x); // 1
console.log(y); // undefined

特定の要素を飛ばすこともできます。

[x,,y,] = [1, 2, 3, 4]; // 1, 3

console.log(x); // 1
console.log(y); // 3

入れ子になっている場合。

let [x, [y, z]] = [1, [2, 3], 4];

console.log(x); // 1
console.log(y); // 2
console.log(z); // 3

オブジェクトの代入

const airports = {
    kix: "Kansai International Airport",
    icn: "Incheon International Airport",
    ala: "Almaty International Airport",
};
const {kix, icn, ala} = airports;

console.log(kix, icn, ala);
// Kansai International
// Airport Incheon International 
// Airport Almaty International Airport

レスト構文

配列から代入する際に、使用されていない残りの値をすべて1つの変数に集めることができます。

let [x, ...y] = [1, 2, 3, 4];

console.log(x); // 1
console.log(y); // [2, 3, 4]

おわりに

今までほとんど使ってこなかったため勉強になりました。

入れ子になったオブジェクトや配列のオブジェクトなど、複雑な分割代入は可読性の下がる可能性がありますが、記述を簡潔にまとめることができるのは大きなメリットです。

適切な箇所で使用し、美しいコードの記述を心がけたいと思います。

それでは。

参考サイト

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