0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】分割代入について

Posted at

分割代入とは

ある配列やオブジェクトの要素を変数として抽出すること。

配列

main.js
const [a, b, c] = ["配列1", "配列2", "配列3"];
console.log(a);
//配列1
console.log(c);
//配列3

配列の場合は、要素の順番ごとに変数を宣言する。

オブジェクト

main.js
const {x, z} = { x: "オブジェクト1", y: "オブジェクト2", z: "オブジェクト3" };
console.log(x);
//オブジェクト1
console.log(z);
//オブジェクト3

オブジェクトの場合は、宣言する名前がそれぞれのプロパティ名に対応する。よって宣言する順番は関係ない。

関数を組み合わせた例

配列

main.js
const array = ["Japan", "Tokyo", "Shinjuku"];
const fnArray = ([country, state, city]) => {
    console.log('country: ${country}');
    console.log('state: ${state}');
    console.log('city: ${city}');
};
fnArray(array);
//country: Japan
//state: Tokyo
//city: Shinjyuku

オブジェクト

main.js
const obj = { country: "Japan", state: "Tokyo", city: "Shinjuku"};
const fnObj = ({ country, state, city }) => {
    console.log('country: ${country}');
    console.log('state: ${state}');
    console.log('city: ${city}');
};
fnObj(obj);
//country: Japan
//state: Tokyo
//city: Shinjyuku

終わり

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?