做一個網頁計算機,UI 用 table 排成按鈕牆,邏輯只需要兩個函式:一個負責把按下的字元接到運算式後面,一個負責求值。核心其實就是 eval()。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>計算機</title>
<script language="javascript" type="text/javascript">
var clearFlag = false;
function getNum(num) {
var objresult = document.getElementById("result");
if (clearFlag) { // 剛按下等號,下一次輸入要重新開始
objresult.value = "";
clearFlag = false;
}
objresult.value += num;
}
function getResult() {
var objresult = document.getElementById("result");
objresult.value = objresult.value + "=" + eval(objresult.value);
clearFlag = true;
}
</script>
</head>
<body>
<table width="200" border="1" cellpadding="2">
<tr>
<td colspan="4"><input type="text" name="result" id="result" size="33"></td>
</tr>
<tr>
<td width="56"><input type="button" value=" 1 " onclick="getNum(1)"></td>
<td width="56"><input type="button" value=" 2 " onclick="getNum(2)"></td>
<td width="51"><input type="button" value=" 3 " onclick="getNum(3)"></td>
<td width="58"><input type="button" value=" + " onclick="getNum('+')"></td>
</tr>
<tr>
<td><input type="button" value=" 4 " onclick="getNum(4)"></td>
<td><input type="button" value=" 5 " onclick="getNum(5)"></td>
<td><input type="button" value=" 6 " onclick="getNum(6)"></td>
<td><input type="button" value=" - " onclick="getNum('-')"></td>
</tr>
<tr>
<td><input type="button" value=" 7 " onclick="getNum(7)"></td>
<td><input type="button" value=" 8 " onclick="getNum(8)"></td>
<td><input type="button" value=" 9 " onclick="getNum(9)"></td>
<td><input type="button" value=" * " onclick="getNum('*')"></td>
</tr>
<tr>
<td><input type="button" value=" 0 " onclick="getNum(0)"></td>
<td><input type="button" value=" . " onclick="getNum('.')"></td>
<td><input type="button" value=" = " onclick="getResult()"></td>
<td><input type="button" value=" / " onclick="getNum('/')"></td>
</tr>
</table>
</body>
</html>
按下等號之後,輸入框裡已經變成「1+2=3」這樣的字串。若使用者接著按數字,顯然應該重新開始而非接在後面,因此 getResult 把 clearFlag 設為 true,下一次 getNum 就先清空再寫入。
沒有清除鍵(AC/C)與退格。這是使用者一定會按的按鈕,必須補上。
沒有連續運算與運算子覆寫。輸入「1 +」之後再按「×」,正確行為應該是把 + 換成 ×,目前會產生「1+×」而求值失敗。
沒有錯誤處理。使用者輸入「1..2」或「1/0」時,eval 會拋 SyntaxError 或直接得到 Infinity,介面上不會有任何提示。應包在 try/catch 中並顯示「錯誤」。
用 eval 求值有安全風險。若日後要支援鍵盤輸入或表達式預先帶入,eval 就成為程式碼注入的入口。替代方案有兩種:一是自己實作運算子優先權的 shunting-yard 演算法,二是引入 math.js 這類專門的運算式解析函式庫。對簡單的四則運算,其實自己寫一個兩段式堆疊求值不到三十行,且完全可控。
鍵盤支援。加上 document.addEventListener('keydown', ...) 對應數字鍵、Enter 與 Escape,才是使用者期待中的計算機。