javascriptの構成要素-独自の関数を作る-

目次

更新履歴

  • 2020/11/03 08:00 初回投稿

この記事の目的

  • javascriptの関しての知識をまとめています.
  • 参考サイトの内容を要約あるいは抜粋,それらの解釈を中心に書いています.
  • 参考サイトの一部または全部が英語のためそれの翻訳を含んでいます.
  • コード上の明らかな間違いがありましたらコメントいただければ幸いです.

関連記事

基本的な関数の作り方

  • 基本形は,function 関数名(引数) {関数の中身}
  • 呼び出しは,イベントに対するレスポンスとすることが多い.
  • 引数を用いて,関数の再利用可能性を高める
btn.onclick = function() {
    BasicCalculation(2,3,'add');
} 

自作関数の例

function BasicCalculation(value1, value2, calcType) {
    const html = document.querySelector('html'); // html要素を格納
    const panel = document.createElement('div'); // div要素を生成
    html.appendChild(panel); // divをhtmlの子要素として追加
    const result = document.createElement('p'); // 結果を格納するp要素
    
// 足し算,引き算,掛け算,割り算かどうかを引数より判定し,計算結果を格納
    if (calcType === 'add') {
        result.textContent = `${value1} + ${value2} = ${value1 + value2}`;
        panel.appendChild(result);
    } else if (calcType === 'subtract') {
        result.textContent = `${value1} - ${value2} = ${value1 - value2}`;
        panel.appendChild(result);
    } else if (calcType === 'multiply') {
        result.textContent = `${value1} * ${value2} = ${value1 * value2}`;
        panel.appendChild(result);
    } else if (calcType === 'devide' && value2 != 0) {
      let value3 = value1 / value2;
        result.textContent = `${value1} / ${value2} = ${value3.toFixed(3)}`; //割り算の桁数は丸める
        panel.appendChild(result);
    }
    // 該当しないかゼロで割っている場合の処理
    else{
    result.textContent = 'No calculation type was found or  cannot devide by zero!';
    panel.appendChild(result);
    }
}
    // イベントにて関数を動かす
    const btn = document.querySelector('button');
    btn.onclick = function() {
    BasicCalculation(2,0,'devide');
    }

参考サイト

独自の関数を作る