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?

More than 1 year has passed since last update.

【Javascript】分割代入の方法まとめ

Last updated at Posted at 2021-12-26

#Javascriptの分割代入とは

分割代入とは、配列の値やオブジェクトのプロパティを取り出して、個別の変数に代入する構文。

###配列の分割代入の構文

{const|let|var} [代入先変数1,代入先変数2] = 代入元配列

###配列の分割代入の具体例

const arr = [ruby,Javascript, python];
const [d1, d2, d3] = arr;
console.log(d1); // -> ruby
console.log(d2); // -> Javascript
console.log(d3); // -> python

上記のように、代入元配列の添字と新たに格納する変数の添字とリンクしていて、左辺の変数に格納されます。一方、分割代入で記述しない場合、以下になります。
記述量が減るため、バグの減少や可読性の向上に繋がります。

const arr = ['ruby','Javascript', 'python'];
const d1 = arr[0]
const d2 = arr[1]
const d3 = arr[2]
console.log(d1); // -> ruby
console.log(d2); // -> Javascript
console.log(d3); // -> python

###オブジェクトの分割代入の構文

[代入先変数1,代入先変数2]代入元オブジェクト 

###オブジェクトの分割代入の具体例

const user1 = {id:1,name:'田中',age:24}
const {id,name,age} = user1
console.log(id); // -> 1
console.log(name); // -> 田中
console.log(age); // -> 24

上記の注意点として、代入元オブジェクトのプロパティ名と代入先の変数名が一致しなければ、値が格納されません。

0
0
2

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?