js实现计算器连续加减
实现连续加减的计算器功能
在JavaScript中实现一个能够处理连续加减的计算器,需要关注表达式解析和运算顺序。以下是实现方法:
基础实现方法
使用eval()函数直接计算字符串表达式:
let expression = '';
function handleButtonClick(value) {
expression += value;
document.getElementById('display').value = expression;
}
function calculate() {
try {
const result = eval(expression);
document.getElementById('display').value = result;
expression = result.toString();
} catch (error) {
document.getElementById('display').value = 'Error';
expression = '';
}
}
function clearDisplay() {
expression = '';
document.getElementById('display').value = '';
}
不使用eval的安全实现
通过解析表达式逐步计算:
let currentValue = 0;
let pendingOperation = null;
let displayValue = '0';
function inputDigit(digit) {
if (displayValue === '0') {
displayValue = digit;
} else {
displayValue += digit;
}
updateDisplay();
}
function handleOperation(nextOperator) {
const inputValue = parseFloat(displayValue);
if (pendingOperation) {
currentValue = performCalculation(currentValue, inputValue, pendingOperation);
} else {
currentValue = inputValue;
}
displayValue = '0';
pendingOperation = nextOperator;
updateDisplay();
}
function performCalculation(firstOperand, secondOperand, operation) {
switch(operation) {
case '+':
return firstOperand + secondOperand;
case '-':
return firstOperand - secondOperand;
default:
return secondOperand;
}
}
function updateDisplay() {
document.getElementById('display').value = displayValue;
}
function clearAll() {
currentValue = 0;
pendingOperation = null;
displayValue = '0';
updateDisplay();
}
处理连续运算的改进方案
维护一个运算队列来支持更复杂的连续运算:
const calculator = {
displayValue: '0',
firstOperand: null,
waitingForSecondOperand: false,
operator: null,
inputDigit(digit) {
const { displayValue, waitingForSecondOperand } = this;
if (waitingForSecondOperand) {
this.displayValue = digit;
this.waitingForSecondOperand = false;
} else {
this.displayValue = displayValue === '0' ? digit : displayValue + digit;
}
},
handleOperator(nextOperator) {
const { firstOperand, displayValue, operator } = this;
const inputValue = parseFloat(displayValue);
if (operator && this.waitingForSecondOperand) {
this.operator = nextOperator;
return;
}
if (firstOperand === null) {
this.firstOperand = inputValue;
} else if (operator) {
const result = this.calculate(firstOperand, inputValue, operator);
this.displayValue = String(result);
this.firstOperand = result;
}
this.waitingForSecondOperand = true;
this.operator = nextOperator;
},
calculate(firstOperand, secondOperand, operator) {
switch(operator) {
case '+': return firstOperand + secondOperand;
case '-': return firstOperand - secondOperand;
default: return secondOperand;
}
},
reset() {
this.displayValue = '0';
this.firstOperand = null;
this.waitingForSecondOperand = false;
this.operator = null;
}
};
注意事项
- 使用
eval()虽然简单但有安全风险,不建议在生产环境使用 - 处理浮点数运算时可能出现精度问题,考虑使用
toFixed()限制小数位数 - 对于更复杂的表达式,可以考虑使用逆波兰算法或构建语法树
- 添加输入验证防止非法字符输入
以上实现方案可以根据具体需求进行调整,第一种方法适合简单场景,后两种方案更适合需要严格控制的商业应用。







