
本文旨在解决基于javascript的计算器在数值输入时无法正确显示的问题。核心原因在于`calculator`类实例的`this.currentoperand`属性未被正确初始化,导致在`appendnumber`方法中尝试操作`undefined`值。通过在构造函数中调用`this.clear()`方法进行初始化,并修正`updatedisplay`方法中的显示逻辑错误,可以彻底解决数值不显示和格式化不当的问题,确保计算器功能正常运行。
在开发基于JavaScript的计算器应用时,一个常见的困扰是当用户点击数字按钮后,预期中的数字并没有显示在屏幕上。根据问题描述,开发者注意到在appendNumber函数中,尝试执行this.currentOperand.toString()时会抛出“Cannot read properties of undefined”的错误。这表明this.currentOperand在被使用之前是undefined,从而导致后续的字符串拼接操作失败。
在提供的Calculator类实现中,constructor方法负责初始化previousOperandTextElement和currentOperandTextElement这两个DOM元素,但并没有对计算器的内部状态变量,如this.currentOperand、this.previousOperand和this.operation进行初始化。
class Calculator {
constructor(previousOperandTextElement, currentOperandTextElement) {
this.previousOperandTextElement = previousOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
// 缺少对 this.currentOperand 等内部状态的初始化
}
// ... 其他方法
}当Calculator类的实例被创建后,this.currentOperand默认为undefined。随后,当用户点击数字按钮并触发appendNumber方法时,代码尝试执行this.currentOperand.toString()。由于undefined没有toString方法,因此会引发运行时错误,导致数字无法附加到当前操作数,进而无法更新显示。
解决this.currentOperand为undefined的问题,最直接有效的方法是在Calculator类的构造函数中调用clear()方法。clear()方法已经定义了将所有操作数和操作符重置为初始状态的逻辑,包括将this.currentOperand设置为空字符串''。
立即学习“Java免费学习笔记(深入)”;
通过在构造函数中调用this.clear(),可以确保在任何数字输入操作发生之前,this.currentOperand已经被正确初始化为一个空字符串,从而避免undefined错误。
class Calculator {
constructor(previousOperandTextElement, currentOperandTextElement) {
this.previousOperandTextElement = previousOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
this.clear(); // 在构造函数中调用 clear() 方法进行初始化
}
// ... 其他方法保持不变
}除了初始化问题,仔细检查updateDisplay()方法,会发现其中存在一个逻辑错误,导致即使this.currentOperand被正确赋值,其格式化后的值也可能未被正确渲染到DOM元素上。
原始的updateDisplay()方法片段:
updateDisplay() {
this.currentOperandTextElement.innerText = this.currentOperand
this.getDisplayNumber(this.currentOperand) // 这一行计算了格式化数字,但没有将其赋值给 innerText
if (this.operation != null) {
this.previousOperandTextElement.innerText = this.previousOperand
`${this.previousOperand} ${this.operation}` // 这一行创建了字符串,但没有将其赋值给 innerText
}
else {
this.previousOperandTextElement.innerText = ''
}
}在JavaScript中,如果两行代码之间没有分号分隔,并且第二行可以作为第一行的延续,解释器可能会尝试将其合并。但在这种情况下,this.getDisplayNumber(this.currentOperand)的返回值被计算了,但并没有被赋值给this.currentOperandTextElement.innerText。同样的问题也存在于previousOperandTextElement的更新逻辑中。
正确的做法是直接将getDisplayNumber的返回值赋给innerText,并使用模板字符串正确拼接前一个操作数和操作符。
修正后的updateDisplay()方法:
updateDisplay() {
// 使用 getDisplayNumber 方法格式化当前操作数并更新显示
this.currentOperandTextElement.innerText = this.getDisplayNumber(this.currentOperand);
if (this.operation != null) {
// 格式化前一个操作数,并与当前操作符一起显示
this.previousOperandTextElement.innerText = `${this.getDisplayNumber(this.previousOperand)} ${this.operation}`;
}
else {
this.previousOperandTextElement.innerText = '';
}
}结合上述两个解决方案,以下是修正后的JavaScript代码:
// script.js
class Calculator {
constructor(previousOperandTextElement, currentOperandTextElement) {
this.previousOperandTextElement = previousOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
this.clear(); // 确保在实例化时初始化所有操作数和操作符
}
clear() {
this.currentOperand = '';
this.previousOperand = '';
this.operation = undefined;
}
delete() {
this.currentOperand = this.currentOperand.toString().slice(0, -1);
}
appendNumber(number) {
if (number === '.' && this.currentOperand.includes('.')) return;
this.currentOperand = this.currentOperand.toString() + number.toString();
}
chooseOperation(operation) {
if (this.currentOperand === '') return;
if (this.previousOperand !== '') {
this.compute();
}
this.operation = operation;
this.previousOperand = this.currentOperand;
this.currentOperand = '';
}
compute() {
let computation;
const prev = parseFloat(this.previousOperand);
const current = parseFloat(this.currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (this.operation) {
case '+':
computation = prev + current;
break;
case '-':
computation = prev - current; // 修正:原始代码中所有操作都是加法
break;
case '*':
computation = prev * current; // 修正
break;
case '÷':
computation = prev / current; // 修正
break;
default:
return;
}
this.currentOperand = computation;
this.operation = undefined;
this.previousOperand = '';
}
getDisplayNumber(number) {
const stringNumber = number.toString();
const integerDigits = parseFloat(stringNumber.split('.')[0]);
const decimalDigits = stringNumber.split('.')[1];
let integerDisplay;
if (isNaN(integerDigits)) {
integerDisplay = '';
}
else {
integerDisplay = integerDigits.toLocaleString('en', {
maximumFractionDigits: 0 });
}
if (decimalDigits != null) {
return `${integerDisplay}.${decimalDigits}`;
}
else {
return integerDisplay;
}
}
updateDisplay() {
// 修正:确保使用 getDisplayNumber 的返回值更新 currentOperandTextElement
this.currentOperandTextElement.innerText = this.getDisplayNumber(this.currentOperand);
if (this.operation != null) {
// 修正:确保使用 getDisplayNumber 的返回值更新 previousOperandTextElement,并正确拼接操作符
this.previousOperandTextElement.innerText = `${this.getDisplayNumber(this.previousOperand)} ${this.operation}`;
}
else {
this.previousOperandTextElement.innerText = '';
}
}
}
const numberButtons = document.querySelectorAll('[data-number]');
const operationButtons = document.querySelectorAll('[data-operation]');
const equalsButton = document.querySelector('[data-equals]');
const deleteButton = document.querySelector('[data-delete]');
const allClearButton = document.querySelector('[data-all-clear]');
const previousOperandTextElement = document.querySelector('[data-previous-operand]');
const currentOperandTextElement = document.querySelector('[data-current-operand]');
const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement);
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendNumber(button.innerText);
calculator.updateDisplay();
});
});
operationButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.chooseOperation(button.innerText);
calculator.updateDisplay();
});
});
equalsButton.addEventListener('click', button => {
calculator.compute();
calculator.updateDisplay();
});
allClearButton.addEventListener('click', button => {
calculator.clear();
calculator.updateDisplay();
});
deleteButton.addEventListener('click', button => {
calculator.delete();
calculator.updateDisplay();
});CSS (styles.css) 和 HTML (index.html) 代码保持不变,因为它们不涉及本次功能修复的核心问题。
/* styles.css */
*, *::before, *::after {
box-sizing: border-box;
font-family: Arial Black, sans-serif;
font-weight: normal;
}
body {
padding: 0;
margin: 0;
background: linear-gradient(to right, #00AAFF, #99e016);
}
.calculator-grid {
display: grid;
justify-content: center;
align-content: center;
min-height: 100vh;
grid-template-columns: repeat(4,100px);
grid-template-rows: minmax(120px,auto) repeat(5,100px);
}
.calculator-grid > button {
cursor: pointer;
font-size: 2rem;
border: 1px solid white;
outline: none;
background-color: rgba(255,255,255,.75);
}
.calculator-grid > button:hover {
cursor: pointer;
font-size: 2rem;
border: 1px solid white;
outline: none;
background-color: rgba(255, 255, 255, 0.95);
}
.span-two {
grid-column: span 2;
}
.output {
grid-column: 1/-1;
background-color: rgba(0,0,0,.75);
display: flex;
align-items: flex-end;
justify-content: space-around;
flex-direction: column;
padding: 10px;
word-wrap: break-word;
word-break: break-all;
}
.output .previous-operand {
color: rgba(255,255,255,.75);
font-size: 1.5rem;
}
.output .current-operand {
color: white;
font-size: 2.5rem;
}<!-- index.html -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link href="styles.css" rel="stylesheet">
<script src="script.js" defer></script>
</head>
<body>
<div class = "calculator-grid">
<div class="output">
<div data-previous-operand class="previous-operand"></div>
<div data-current-operand class="current-operand"></div>
</div>
<button data-all-clear class="span-two">AC</button>
<button data-delete>DEL</button>
<button data-operation> ÷ </button>
<button data-number> 1 </button>
<button data-number> 2 </button>
<button data-number> 3 </button>
<button data-operation> * </button>
<button data-number> 4 </button>
<button data-number> 5 </button>
<button data-number> 6 </button>
<button data-operation> + </button>
<button data-number> 7 </button>
<button data-number> 8 </button>
<button data-number> 9 </button>
<button data-operation> - </button>
<button data-number> . </button>
<button data-number> 0 </button>
<button data-equals class="span-two">=</button>
</div>
</body>
</html>注意: 在compute()方法中,原始代码对所有操作符(减、乘、除)都执行了加法运算。上述完整代码示例中已将这些错误修正为正确的运算逻辑。
通过以上修正,JavaScript计算器将能够正确显示用户输入的数字,并执行预期的计算功能。
以上就是JavaScript计算器开发指南:解决显示异常与代码改进的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号