👻

【JavaScript】分割代入

に公開
  • 配列やオブジェクトの各要素を、順番に定数/変数に代入する命令
  • 括弧[]{}を使うので、配列やオブジェクトを定義しているように間違いがちだが、右側に配列名やオブジェクト名が記述してあったら分割代入のための記号だと認識できる
  • 値の入れ替えによく使われる

配列

const scores = [65, 37, 85, 69, 94];
const [first, socond, third, fourth, fifth] = scores; // 自由に変数名を割り当てる
// 下記と同じ処理
// const first = scores[0];
// const socond = scores[1];
// const third = scores[2];
// const fourth = scores[3];
// const fifth = scores[4];

console.log(first);
console.log(socond);
console.log(third);
console.log(fourth);
console.log(fifth);

let start = 'Tokyo';
let goal = 'Fukuoka';

[goal, start] = [start, goal]; // 配列にして、値を入れ替えることができる
// 下記と同じ処理
// let temp = start;
// start = goal;
// goal = temp;

オブジェクト

const profile = {
    name: Yoshio,
    age: 24,
};

const {name, age} = profile; // 取り出したいプロパティ名を指定
const {name = 'ゲスト', age} = profile; // デフォルト値も設定できる
console.log(`名前は${name}。年は${age}`);

Discussion