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

1. 配列の展開(Spread)

const arr1 = [1, 2];
const sumFunc = (num1, num2) => console.log(num1 + num2);

sumFunc(arr1[0], arr1[1]); // 3
sumFunc(...arr1);          // 3(バラバラに展開して渡している)

2. まとめる(Rest parameters)

const arr3 = [1, 2, 3, 4, 5];
const [num1, num2, ...rest] = arr3; // 残りを「rest」としてまとめる
console.log(num1); // 1
console.log(num2); // 2
console.log(rest); // [3, 4, 5]

3. 配列のコピー、結合

const arr4 = [10, 20];
const arr5 = [30, 40];

// 新しい配列としてコピー(元のarr4には影響しない)
const arr6 = [...arr4]; 

// 配列の結合
const arr7 = [...arr4, ...arr5]; // [10, 20, 30, 40]

// 【注意】参照のコピー(非推奨なやり方)
const arr8 = arr4; 
// arr8を変更すると、大元のarr4も書き換わってしまうため、
// 基本的にはスプレッド構文でのコピーが推奨されます。
0
0
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
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?