LoginSignup
4
3

More than 3 years have passed since last update.

JavaScript | 分割代入 (配列, オブジェクト)

Last updated at Posted at 2019-08-25

分割代入ってなんじゃらほい

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

OK!!めっちゃ便利そうなコンセプトだから例を作りながらチェックしてゆく
まずはobjっていうオブジェクトを用意します

const obj = { x: 1, y: 2 };

objのプロパティを取り出して別個の変数に代入する...
ぱっと思いつくのはこんなやつ


let x_ = obj.x;
let y_ = obj.y;

console.log(x_);
console.log(y_):

// 期待する出力結果
// 1
// 2

もっとシンプルな書き方があるらしい


let { x: x_, y: y_ } = obj;

console.log(x_);
console.log(y_);

// 期待する出力結果
// 1
// 2

もし代入したい変数の名前をオブジェクトのプロパティと同じにしたいなら、もっと簡単な書き方があるらしい

let { x, y } = obj;

console.log(x)
console.log(y)

// 期待する出力結果
// 1
// 2

配列の場合
const arr = [1, 2];

let [x, y] = arr;

console.log(x)
console.log(y)

// 期待する出力結果
// 1
// 2

単純にxだけy無しで定義してみる
そうすると一番最初の値がきちんと取れる

const arr = [1, 2];

let [x] = arr;

console.log(x)

// 期待する出力結果
// 1

参考にしたい記事

4
3
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
4
3