目次
更新履歴
この記事の目的
- javascriptの関しての知識をまとめています.
- 参考サイトの内容を要約あるいは抜粋,それらの解釈を中心に書いています.
- 参考サイトの一部または全部が英語のためそれの翻訳を含んでいます.
- コード上の明らかな間違いがありましたらコメントいただければ幸いです.
関連記事
- その1(立ち位置,主な機能,変数,数値と演算子)はこちら
- その2(文字列と配列)はこちら
- その3(条件式と繰り返し文)はこちら
- その4(関数)はこちら
基本的な関数の作り方
- 基本形は,
function 関数名(引数) {関数の中身}
- 呼び出しは,イベントに対するレスポンスとすることが多い.
- 引数を用いて,関数の再利用可能性を高める
btn.onclick = function() {
BasicCalculation(2,3,'add');
}
自作関数の例
function BasicCalculation(value1, value2, calcType) {
const html = document.querySelector('html');
const panel = document.createElement('div');
html.appendChild(panel);
const result = document.createElement('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');
}
参考サイト
独自の関数を作る