LoginSignup
0
2

More than 3 years have passed since last update.

Javascriptの関数で可変長引数を配列として利用する方法 | Array.prototype.slice.call()

Last updated at Posted at 2020-02-18

*この記事は、「Javascriptで可変長引数をスグにでも使いたい」と言う人を対象に書いております。細かいことは省いていますので、突っ込んだことを知りたい方は他のページを調べてください。

Rubyには普通に存在する可変長引数ですが、Javascriptで利用するには少し工夫が必要になります。

と言っても、Array.prototype.slice.call()を使うだけです。

以下、例をあげます。

hatsumori.js
var test = function() {
  var args = Array.prototype.slice.call(arguments);
  console.log(args);
}

test('ななまる', 'イマドキ', 'ショパン', 'アカデミー')
// ['ななまる', 'イマドキ', 'ショパン', 'アカデミー']

関数内でargumentsは渡された引数を渡してくるのですが、そのままでは「配列っぽい何か」であり、配列として加工できません。
Array.prototype.slice.call(arguments)で、配列として加工できるようになります。

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