" />
本ページはプロモーションが含まれています。

スポンサーリンク

TypeScript

JavaScriptの分割代入

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

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

オブジェクトの分割代入

基本

const myProfile = {
  name: "鈴木",
  age: 35,
}

const {name, age} = myProfile;

console.log(name); // => 鈴木
console.log(age);   // => 35

デフォルト値を設定する

const myProfile = {
  name: "鈴木",
  age: 35,
}

const {sex = "女"} = myProfile;

console.log(sex); // => 女

配列の分割代入

基本

const horses = ["トウカイテイオー", "オグリキャップ", "シンザン"];

const [horse1 , horse2] = horses;

console.log(horse1); // => トウカイテイオー
console.log(horse2); // => オグリキャップ

デフォルト値を設定する

const horses = ["トウカイテイオー", "オグリキャップ", "シンザン"];

const [horse1, horse2, horse3, horse4 = "ビワハヤヒデ"] = horses;

console.log(horse4); // => ビワハヤヒデ

スポンサーリンク

-TypeScript