2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptの分割代入って?

2
Posted at

はじめに

今までJavaScritpの分割代入という機能を知らなかったので、簡単にまとめます。

問題

分割代入の構文ってどうやって書くの?

解決方法

分割代入とは?

■オブジェクトの場合
従来はこのように「.」で参照する必要があります。

const myProfile = {
  name: 'じゃけえ',
  age: 31,
};

const message1 = `名前は${myProfile.name}です。年齢は${myProfile.age}歳です。`;

ですが、分割代入を使用すると

const { name, age } = myProfile;
const message2 = `名前は${name}です。年齢は${age}歳です。`;

これだけで済みます◎

■配列の場合
従来はこのように順番を指定してあげる必要があります。

const myProfile = ['じゃけえ', 31];
const message1 = `名前は${myProfile[0]}です。年齢は${myProfile[1]}歳です。`;

ですが、分割代入を使用すると

const [name, age] = myProfile;
const message2 = `名前は${name}です。年齢は${age}歳です。`;

これで済みます◎
配列の場合は好きな変数を[]に指定してあげる必要があります。
また、格納先の変数には配列の順番通りに格納されるので注意してください。

おわりに

短くかけるのは便利なので積極的に使用していきましょう!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?