背景
勉強中に「あれ、これってなんだっけ...」となることが多いので思い切ってまとめます!
勉強の効率を上げましょう!
分割代入ってなに?
オブジェクト・配列に対して使用します。
手動で一つ一つ取り出すよりも簡潔かつ可読性の高いコードにすることができます。
オブジェクトの分割代入
オブジェクトのプロパティを取り出します。
const person = {
name: "Tom",
age: 25,
email: "tom@example.com"
};
// 分割代入でnameとemailを取り出す
const { name, email } = person;
console.log(name); // "Tom"
console.log(email); // "tom@example.com"
プロパティ名を変更して代入
変数名を変更する場合、新しい変数名を指定できます。
const person = {
name: "Tom",
age: 25,
email: "tom@example.com"
};
// 変数名を変更して取り出す
const { name: userName, email: userEmail } = person;
console.log(userName); // "Tom"
console.log(userEmail); // "tom@example.com"
デフォルト値を設定する
オブジェクトにプロパティがなかった場合にデフォルト値を設定できます。
const person = {
name: "Tom",
//emailなし
};
// emailがない場合、デフォルト値として"unknown@example.com"を設定
const { name, email = "unknown@example.com" } = person;
console.log(name); // "Tom"
console.log(email); // "unknown@example.com"
配列の分割代入
配列の各要素を変数に取り出す方法です。
const colors = ["red", "green", "blue"];
// 分割代入で配列の要素を取り出す
const [color1, color2, color3] = colors;
console.log(color1); // "red"
console.log(color2); // "green"
console.log(color3); // "blue"
必要な要素のみを取り出すことも可能です。
// 最初の2つを取り出し、3番目は無視
const colors = ["red", "green", "blue"];
// 2番目をスキップしたいので、 , で飛ばす
const [first, , third] = colors;
console.log(first); // "red"
console.log(third); // "blue"
デフォルト値を設定する
const colors = ["red"];
// 2番目と3番目の要素はデフォルト値を設定
const [color1, color2 = "green", color3 = "blue"] = colors;
console.log(color1); // "red"
console.log(color2); // "green"(デフォルト値)
console.log(color3); // "blue"(デフォルト値)
ネストされた分割代入
オブジェクトや配列がさらにネストされた場合でも分割代入を使って簡単に取り出すことができます。
オブジェクトの場合
const person = {
name: "Tom",
address: {
city: "New York",
zip: "10001"
}
};
// addressオブジェクトのcityとzipを分割代入
const { name, address: { city, zip } } = person;
console.log(name); // "Tom"
console.log(city); // "New York"
console.log(zip); // "10001"
配列の場合
const colors = [["red", "green"], ["blue", "yellow"]];
// ネストされた配列を分割代入で取り出す
const [[color1, color2], [color3, color4]] = colors;
console.log(color1); // "red"
console.log(color2); // "green"
console.log(color3); // "blue"
console.log(color4); // "yellow"
まとめ
分割代入は、複雑なデータをスッキリとシンプルに扱える便利な機能です!
ReactやTypeScriptの開発では頻出らしいので、手足のように扱えるよう習得を目指します!