javascript 引数に引数を使用する
- 2020.09.20
- javascript
- javascript

javascriptで、関数の引数を同じ関数の引数として使用するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ firefox 80.0.1
引数利用
以下のように、関数の引数を、引数に使用することが可能です。
※引数は、左側から評価されます。
1 2 3 4 5 6 |
function hoge(msg1, msg2 = msg1 + 'world') { console.log(msg1, msg2); } hoge('hello'); // hello helloworld hoge('text1','text2'); // text1 text2 |
サンプルコード
以下は、
「実行」ボタンをクリックすると、フォームに入力された値を第1引数にして、第2引数で、その第1引数を使用した結果を表示する
サンプルコードとなります。
※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 54 55 56 57 58 59 60 61 |
<!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"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> function hoge(msg1, msg2 = msg1 + 'world') { // 表示用の要素 var elm = document.getElementById("foo"); // 引数を表示 elm.textContent = msg2; } window.onload = function () { var elm = document.getElementById("btn"); // クリックイベントを設定 elm.onclick = function () { // フォームの値を取得 var str = document.getElementById("txtfrm").value; // フォームの値を第1引数に指定 hoge(str); }; } </script> <body> <div class="main"> <h2 id="foo" class="badge badge-primary">文字列を表示</h2> <div class="form-group"> <label for="formGroupExampleInput" class="bmd-label-floating">hogeの第1引数を指定</label> <input id="txtfrm" type="text" class="form-control"> </div> <button id="btn" type="button" class="btn btn-raised btn-danger"> 実行 </button> </div> </body> </html> |
第1引数が第2引数に利用されていることが確認できます。

-
前の記事
javascript 引数の初期値を設定する 2020.09.20
-
次の記事
javascript replaceの正規表現に変数を利用する 2020.09.20
コメントを書く