2
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 3 years have passed since last update.

[JS]スプレット構文について

2
Posted at

はじめに

Javascriptでスプレット構文を使ったので勉強用として残しておきます。

使い方

公式ドキュメントではスプレット構文について以下のように書かれています。

スプレッド構文 (...) を使うと、配列式や文字列などの反復可能オブジェクトを、0 個以上の引数 (関数呼び出しの場合) や要素 (配列リテラルの場合) を期待された場所で展開したり、オブジェクト式を、0 個以上のキーと値のペア (オブジェクトリテラルの場合) を期待された場所で展開したりすることができます。

言葉だけだとちょっとわかりにくいですね。
例文を見てみましょう。

const argumentArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'];

console.log(argumentArray);
// ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']

※スプレット構文の場合
console.log(...argumentArray);
// a b c d e f g h i j k l m n

以上のように配列になっている変数に...を変数名の前に付け加えると14個の配列が展開されることがわかります。
また、以下のように関数に対してもスプレット構文は使えます。

function getData() {
     const argumentArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'];
     return argumentArray
}

console.log(...getData())
// ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]

※スプレット構文の場合
console.log(getData())
// a b c d e f g h i j k l m n

参考

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