简易计算器
使用 JavaScript 实现的基本四则运算计算器
核心代码 现代模式
// 使用 ES6 类和模块化
class Calculator {
constructor() {
this.display = document.getElementById('display');
this.currentValue = '0';
this.previousValue = '';
this.operation = null;
this.shouldResetScreen = false;
this.initializeEventListeners();
}
updateDisplay() {
this.display.value = this.currentValue;
}
appendNumber(number) {
if (this.currentValue.replace('.', '').length >= 12) return;
if (this.currentValue === '0' || this.shouldResetScreen) {
this.currentValue = number;
this.shouldResetScreen = false;
} else {
this.currentValue += number;
}
this.updateDisplay();
}
appendOperator(operator) {
if (this.operation !== null) this.calculate();
this.previousValue = this.currentValue;
this.operation = operator;
this.shouldResetScreen = true;
}
calculate() {
if (this.operation === null || this.shouldResetScreen) return;
const prev = parseFloat(this.previousValue);
const current = parseFloat(this.currentValue);
if (isNaN(prev) || isNaN(current)) return;
const result = this.performCalculation(prev, current);
this.currentValue = result.toString();
this.operation = null;
this.previousValue = '';
this.shouldResetScreen = true;
this.updateDisplay();
}
performCalculation(prev, current) {
switch (this.operation) {
case '+': return prev + current;
case '-': return prev - current;
case '×': return prev * current;
case '÷': return prev / current;
default: return current;
}
}
}