LoginSignup
4
3

More than 1 year has passed since last update.

Javascriptの豆知識(...について)

Posted at

背景

最近のJavascriptのコードを見たら、よく...を見ます。私は2014以降では業務上でjavascriptを触っていないため、最初...を見る時に、不思議でした。

役割

残余引数(rest parameters)

ES6以降では、...を残余引数として使えるようになりました。

const test = (a,...args) => {
    console.log(a)
    console.log(args)
}
test("a",1,2,3,4,5)
a <- 1番目の引数です
[ 1, 2, 3, 4, 5 ] <- ...argsです、一つの配列にまとめています。

...argsは残余引数になります。

注意点としては、
...argsを引数の最後に位置付ける必要があります
...argsにデフォルト値を与えることはできないです
...argsの可能な値は配列です、undefinedまた単一な値になることはないです

参考リンク
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/rest_parameters

スプレッド構文

残余引数はたくさんの引数を一つの配列にまとめることです
スプレッド構文は逆の役割をもっています。一つの配列を一つずつの関数の引数や要素に展開します。

const arr = [1,2,3]
console.log(arr)
console.log(...arr)
console.log(["a",...arr])
[ 1, 2, 3 ] <- 元な配列
1 2 3 <- 展開した配列
[ 'a', 1, 2, 3 ] <- 展開した配列

参考リンク
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Spread_syntax

4
3
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
4
3