20
24

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.

argumentsの簡単な使用例

Posted at

js勉強中です。
argumentsの使い方を教えてもらったのでメモ。


例えば

js
var sum = function (a,b,c,d,e) {
  return a + b + c + d + e;
}
sum(1,2,3,4,5);

このとき引数が100個とかになると大変
そんなときにargumentsを使うと便利

js
var sum = function(){
  var total = 0;
  for (var i=0 ; i<arguments.length ; i++){
    total += arguments[i];
  }
  return total;
}
sum(1,2,3,4,5,.....,100);

とか

js
var sum = function(){
  var total = 0;
  var args = Array.prototype.slice.call(arguments);
  for (var i=0 ; i<args.length ; i++){
    total += args[i];
  }
  return total;
}
sum(1,2,3,4,5,.....,100);



以下宿題

js
sum(1,2,3,4,5,"test",[]);

みたいに文字列とか配列が入ったときに、
足さないようにconstructorを使ってなんとかする

20
24
2

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
20
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?