LoginSignup
1
0

More than 1 year has passed since last update.

Javascriptで引数の数が未定だがとりあえず関数を作りたい【残余引数】

Posted at

function 関数名(...引数) ||
(...引数) => {}

不特定数の引数を受け取る関数を作りたい

不特定多数の引数を受け取るには「...引数」のように「...」を用いる。
受け取った引数は引数[0],引数[1]のようにインデックスを使用して使用可能。残余引数という。

渡した引数を全て加算してreturnする関数はこちら。

function calcSum(...prices){
 let result = 0;
 for(const value of prices){
   result += value;
}
 return result;
}

const result1 = calcSum(10,20)
1
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
1
0