18
17

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

ES6で可変長の引数に配列を渡す

Last updated at Posted at 2015-08-12

ES6の可変長の引数に配列を渡すやり方がわかりやすくなってたので調べてみた。

可変長の引数は下記のように数に指定なく複数の引数を渡せる。

js
function test() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

test("あ","い","う");
// -> あいう
test("あ","い","う","え","お");
// -> あいうえお

複数の引数を受け取り関数内でargumentから値をとりだしている処理に対して、配列を渡したい場合、ES5では下記のようにapplyを使い書く。

js
function test() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

var aiu = ["あ","い","う"];
test.apply(null, aiu); // -> あいう

ES6では、下記のようにスプレッドオペレータを使い書ける。

js
var aiu = ["あ","い","う"];
test(...aiu); // -> あいう

配列を展開してくれる機能のスプレッドオペレータがES6では実装されているので、読みやすいコードが書けるようになった。

18
17
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
18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?