1
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

はじめに

JavaScript の ... には大きく分けて 2 種類の使い方があります。

  • スプレッド構文(Spread syntax)展開する
  • レスト構文(Rest syntax)まとめる

それぞれどのような使い方をするのか、実際にコードを書いて整理していきます。

スプレッド構文

1. 展開する

配列を要素ごとに展開して渡せます。

const numbers = [1, 2];
const sum = (a, b) => console.log(a + b);

sum(...numbers); // 3
// sum(numbers[0], numbers[1]) と同じ

2. コピーする(非破壊)

スプレッド構文を使うと元のデータを変更せずにコピーできます。

const fruits = ["apple", "banana"];

// 危険:参照コピー
const refCopy = fruits;
refCopy[0] = "grape";
console.log(fruits); // ["grape", "banana"]

// 安全:スプレッドコピー
const copy = [...fruits];
copy[0] = "orange";
console.log(copy);   // ["orange", "banana"]
console.log(fruits); // ["apple", "banana"]

また、元の配列を変えずに加工することもできます。

const fruits = ["apple", "banana", "grape"];
const reversed = [...fruits].reverse();

console.log(reversed); // ["grape", "banana", "apple"]
console.log(fruits);   // ["apple", "banana", "grape"]

3. 結合する

複数の配列を結合できます。

const fruits1 = ["apple", "banana"];
const fruits2 = ["grape", "orange"];

const allFruits = [...fruits1, ...fruits2];
console.log(allFruits); // ["apple", "banana", "grape", "orange"]

オブジェクトでも同様にスプレッド構文を使えます。

const morningMenu = {
  breakfast: "トースト",
  lunch: "カレー"
};

const dinnerMenu = "ラーメン";

const fullDayMenu = {
  ...morningMenu,
  dinner: dinnerMenu
};

console.log(fullDayMenu);
// {
//   breakfast: "トースト",
//   lunch: "カレー",
//   dinner: "ラーメン"
//  }


レスト構文

まとめる

配列やオブジェクトの「残りの部分」をまとめて受け取れます。

const fruits = ["apple", "banana", "grape", "orange", "melon"];
const [first, second, ...rest] = fruits;

console.log(first);  // "apple"
console.log(second); // "banana"
console.log(rest);   // ["grape", "orange", "melon"]

関数の引数をまとめる(残余引数)こともできます。

function showFruits(...items) {
  console.log(`全部で${items.length}種類のフルーツがあります`);
}

showFruits("apple", "banana", "grape");
// 全部で3種類のフルーツがあります

まとめ

  • スプレッド構文は「広げる」
  • レスト構文は「集める」

というイメージを持つと、使い分けが分かりやすくなりそうです!

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