javascript 関数の引数をカウントする
- 2020.10.11
- javascript
- javascript

javascriptでlengthを使用して、関数の引数をカウントするサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
length使い方
lengthを使うと、関数に存在する引数の数を取得することができます。
1 |
関数名.length |
lengthメソッド使い方
1 2 3 4 5 6 7 8 |
function hoge() { console.log(foo.length); // 3 } function foo(val1,val2,val3) { } |
サンプルコード
以下は、「カウント」ボタンをクリックすると、各関数の引数の数を表示するだけのサンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 150px; display: flex; flex-direction: column; align-items: center; font-size: 20px; } </style> <script> function hoge() { document.getElementById('foo').textContent = foo.length; document.getElementById('bar').textContent = bar.length; document.getElementById('piyo').textContent = piyo.length; } function foo(val1,val2,val3) {} function bar(val1) {} function piyo() {} </script> <body> <div class="main"> <ul class="list-group"> <li id="foo" class="list-group-item list-group-item-primary">foo関数の引数の数</li> <li id="bar" class="list-group-item list-group-item-secondary">bar関数の引数の数</li> <li id="piyo" class="list-group-item list-group-item-success">piyo関数の引数の数</li> </ul> <button type="button" class="btn btn-raised btn-primary" onclick="hoge()">カウント</button> </div> </body> </html> |
正しく引数がカウントされていることが確認できます。

-
前の記事
javascript メソッド定義構文を使用する 2020.10.11
-
次の記事
javascript newを使ってオブジェクトを生成する 2020.10.11
コメントを書く