新闻中心
J*aScript计算器开发指南:解决显示异常与代码改进

本文旨在解决基于j*ascript的计算器在数值输入时无法正确显示的问题。核心原因在于`calculator`类实例的`this.currentoperand`属性未被正确初始化,导致在`appendnumber`方法中尝试操作`undefined`值。通过在构造函数中调用`this.clear()`方法进行初始化,并修正`updatedisplay`方法中的显示逻辑错误,可以彻底解决数值不显示和格式化不当的问题,确保计算器功能正常运行。
问题现象与初步分析
在开发基于J*aScript的计算器应用时,一个常见的困扰是当用户点击数字按钮后,预期中的数字并没有显示在屏幕上。根据问题描述,开发者注意到在appendNumber函数中,尝试执行this.currentOperand.toString()时会抛出“Cannot read properties of undefined”的错误。这表明this.currentOperand在被使用之前是undefined,从而导致后续的字符串拼接操作失败。
根本原因:未初始化的 this.currentOperand
在提供的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设置为空字符串''。
通过在构造函数中调用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 = ''
}
}在J*aScript中,如果两行代码之间没有分号分隔,并且第二行可以作为第一行的延续,解释器可能会尝试将其合并。但在这种情况下,this.getDisplayNumber(this.currentOperand)的返回值被计算了,但并没有被赋值给this.currentOperandTextElement.innerText。同样的问题也存在于previousOperandTextElement的更新逻辑中。
Waifulabs
一键生成动漫二次元头像和插图
317
查看详情
正确的做法是直接将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 = '';
}
}完整代码示例
结合上述两个解决方案,以下是修正后的J*aScript代码:
// 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}`;
}
el
se {
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()方法中,原始代码对所有操作符(减、乘、除)都执行了加法运算。上述完整代码示例中已将这些错误修正为正确的运算逻辑。
关键点与最佳实践
- 类状态的初始化: 任何类在其实例化时,都应确保其内部状态变量被正确初始化。这可以防止在后续方法调用中出现undefined或null相关的运行时错误。对于复杂状态,可以封装一个初始化方法(如本例中的clear())并在构造函数中调用。
- 仔细检查显示逻辑: 当数据正确处理但界面显示不正确时,应重点检查负责更新UI的逻辑。确保函数返回值被正确使用,并且DOM元素的属性(如innerText)被正确赋值。
- 调试技巧: 利用浏览器开发者工具(Console、Sources面板)是定位此类问题的关键。通过设置断点、检查变量值(特别是this对象的状态),可以清晰地看到代码执行流程中变量的变化,从而快速发现问题所在。
- 代码审查: 定期进行代码审查,或使用静态代码分析工具,有助于发现潜在的逻辑错误和语法问题,尤其是在团队协作或代码交接时。
通过以上修正,J*aScript计算器将能够正确显示用户输入的数字,并执行预期的计算功能。
以上就是J*aScript计算器开发指南:解决显示异常与代码改进的详细内容,更多请关注其它相关文章!
# 美食网站域名推广排名
# 这一行
# 都是
# 并在
# 空字符串
# 相关文章
# 这两个
# 大同关键词排名提升软件
# 建设网站顺序
# 未被
# 攀枝花网站推广费用
# 小红书的网站推广
# 襄阳服装网站推广开户
# 东阳抖音推广营销中心
# 外贸独立网站推广怎么做
# 网站建设微企
# 手机app推广营销模式
# css
# 是在
# 将其
# 返回值
# swi
# 工具
# edge
# app
# 浏览器
# seo
# git
# js
# html
# java
# word
# javascript
相关栏目:
【
科技资讯46185 】
【
网络学院92790 】
相关推荐:
腾讯QQ邮箱登录入口_QQ邮箱官方网站使用地址
C++ typeid如何获取类型信息_C++ RTTI运行时类型识别用法
Angular中单选按钮的正确使用与常见陷阱解析
2025-2030年全球乘用车销量预测:新能源成增长主力
AO3官方在线访问地址 Archive of Our Own最新镜像合集
优酷会员付费后没到账怎么办_优酷会员充值异常及解决方法
如何创建独立于主系统的J*a运行环境_隔离式环境搭建策略
腾讯视频怎么使用多账号家庭管理_腾讯视频家庭多账号统一管理与权限分配教程
QQ邮箱网页版登录入口 QQ邮箱官方在线使用平台
汽水音乐网页版使用入口_汽水音乐电脑版播放指南
如何使用Rector自动化升级旧代码_通过Composer安装和配置Rector进行代码重构
C++如何打印当前代码行号与文件名_C++预定义宏FILE与LINE的使用
vivo浏览器怎么扫描二维码 vivo浏览器内置扫一扫功能使用方法
J*aScript生成器_j*ascript异步迭代
深入理解Google Cloud Datastore查询:祖先路径与数据一致性
QQ邮箱网页版快速登录 QQ邮箱邮箱账号官方入口地址
2025年云电脑操作系统体验 | 无需本地硬件,随时随地使用高性能PC
文心一言怎样用批量生成做多版文案_文心一言用批量生成做多版文案【批量创作】
windows10怎么查看本机ip_windows10命令提示符ipconfig使用
Go语言中JSON数据解码与字段访问指南
win11如何卸载Windows更新补丁 Win11解决更新导致系统不稳定的问题【修复】
msn官网入口地址手机版 msn官方网站手机最新链接
AO3同人作品网入口 AO3搜索引擎官网永久地址
uc手机浏览器网页版入口 uc浏览器手机版便捷登录首页
Node.js CSV 数据处理:基于字段值条件过滤整条记录的策略
Spring Boot嵌入式服务器与J*a EE:功能支持深度解析
2025AO3夸克浏览器通道_AO3手机HTTPS安全入口分享
蛙漫限时开放最深处链接_蛙漫全站漫画会员同款秒开地址
铃兰之剑为这和平的世界希里技能组及加点推荐
知乎APP怎么管理已购盐选内容_知乎APP盐选内容购买记录与查看方法
QQ官网正版登录链接 QQ在线登录入口最新
Go语言JSON解析深度指南:动态访问与结构体映射实践
Win11如何使用Windows Sandbox Win11沙盒功能开启与使用教程【详解】
漫蛙漫画官方首页 漫蛙2漫画在线阅读入口
深入理解J*a编译器的兼容性选项:从-source到--release
正确连接J*aScript到HTML实现可点击图片与自定义事件处理
J*a里如何使用forEach遍历Map_Map遍历方法说明
Pygame教程:解决用户输入与游戏状态更新不同步问题
HTML元素状态管理:根据DIV内容动态启用/禁用按钮
J*aScript:在map操作中高效处理空数组
J*aScript 字符串标签转换:使用正则表达式高效替换
2306选座时如何选靠窗位置_12306选座靠窗座位查看方法解析
淘宝支付提示失败如何解决 淘宝支付流程优化方法
age动漫网站入口 age动漫官网直接访问入口
PHP中SSG-WSG API的AES加密实践:正确使用初始化向量
vivo浏览器自带的下载器速度慢怎么办 vivo浏览器提升文件下载速度的技巧
在J*a里如何理解依赖关系的方向_依赖方向在模块结构中的作用
c++ 命名空间怎么用 c++ namespace使用指南
Win11 USB传输速度慢怎么解决 Win11 USB驱动更新与设置
深入理解J*aScript中的B样条曲线与节点向量生成


2025-11-21
浏览次数:次
返回列表
se {
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();
});