初學 JS 寫計算器時,常遇到一個「加法變拼接」的坑:
x = window.prompt("請輸入第一個數字:");
y = window.prompt("請輸入第二個數字:");
// 用戶輸入 1 和 2
alert(x + y); // 彈出 "12" 而不是 3
prompt、input.value、textarea.value 返回的**都是字符串**。JS 中 + 運算符同時承擔「數字相加」與「字符串拼接」,只要任一操作數是字符串,就觸發拼接。
let a = parseInt(prompt("整數:"), 10); // 基數 10 防八進制誤解
let b = parseFloat(prompt("小數:"));
let a = Number(prompt("數字:")); // 無法解析返回 NaN
let b = +prompt("數字:"); // 簡寫,同 Number()
let a = prompt("數字:") * 1; // 隱式轉換
function calc() {
const x = Number(prompt("第一個數字:"));
const y = Number(prompt("第二個數字:"));
const op = prompt("運算符 + - * / :");
let result;
switch (op) {
case '+': result = x + y; break;
case '-': result = x - y; break;
case '*': result = x * y; break;
case '/': result = y !== 0 ? x / y : '除數不能為0'; break;
default: result = '未知運算符';
}
alert(`結果: ${result}`);
}
if (isNaN(x) || isNaN(y)) return alert('請輸入合法數字');* 100 轉整數運算,最後 / 100,或用 toFixed(2)。eval():安全風險極大,嚴禁生產環境使用。牢記「所有用戶輸入默認是字符串,運算前必須顯式轉型」,JS 基礎大廈才穩固。