不用任何套件,幾個 input、一個 select 加上一段 switch,就能做出一個四則運算的計算器。很適合當作 JavaScript 基礎練習。

<!DOCTYPE html>
<html>
<head>
<title>簡易計算器</title>
<script type="text/javascript">
function count() {
var txt1 = parseInt(document.getElementById('txt1').value); // 第一個數字
var txt2 = parseInt(document.getElementById('txt2').value); // 第二個數字
var select = document.getElementById('select').value; // 運算子
var result = '';
switch (select) {
case '+': result = txt1 + txt2; break;
case '-': result = txt1 - txt2; break;
case '*': result = txt1 * txt2; break;
case '/': result = txt1 / txt2; break;
}
document.getElementById('fruit').value = result; // 寫回結果
}
</script>
</head>
<body>
<input type="text" id="txt1" />
<select id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="txt2" />
<input type="button" value=" = " onclick="count()" />
<input type="text" id="fruit" />
</body>
</html>
getElementById 取得兩個輸入框與下拉選單。parseInt 把字串轉成整數(注意:input 的 value 永遠是字串)。switch 依運算子計算。value。1、parseInt 丟掉小數。parseInt("3.7") 只會得到 3。要支援小數請改用 parseFloat;若要處理使用者輸入的各種格式,Number(x) 更合適(空字串會變成 0,非數字會變成 NaN)。
2、沒有任何輸入驗證。留空、輸入文字、除數為 0 都會產生 NaN 或 Infinity。建議加一段檢查:
function count() {
var a = Number(document.getElementById('txt1').value);
var b = Number(document.getElementById('txt2').value);
var op = document.getElementById('select').value;
var out = document.getElementById('fruit');
if (isNaN(a) || isNaN(b)) { out.value = '請輸入有效數字'; return; }
if (op === '/' && b === 0) { out.value = '除數不可為 0'; return; }
var result;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = a / b; break;
}
out.value = result;
}
3、用 === 做嚴格比較。switch 比對時用嚴格相等可以避免型別轉換帶來的意外。
4、結果欄位應該用 readonly。結果是輸出而不是輸入,加上 readonly 屬性比較符合語意,也能避免使用者誤改。
想再往前一步,可以試著做這些改進:
keydown)。try/catch 或一個簡單的算式解析器支援連續運算,例如 1 + 2 * 3;若要正式做,可以研究 eval 的替代方案或自己寫一個 shunting-yard 演算法。這個練習的重點其實不在計算本身,而在熟悉「取值 → 轉型 → 分支 → 寫回」這個 DOM 操作的基本迴路,後面做任何表單互動都是同一套模式。