0

0

JavaScript计算器开发指南:解决显示异常与代码改进

心靈之曲

心靈之曲

发布时间:2025-11-21 11:35:24

|

378人浏览过

|

来源于php中文网

原创

JavaScript计算器开发指南:解决显示异常与代码改进

本文旨在解决基于javascript的计算器在数值输入时无法正确显示的问题。核心原因在于`calculator`类实例的`this.currentoperand`属性未被正确初始化,导致在`appendnumber`方法中尝试操作`undefined`值。通过在构造函数中调用`this.clear()`方法进行初始化,并修正`updatedisplay`方法中的显示逻辑错误,可以彻底解决数值不显示和格式化不当的问题,确保计算器功能正常运行。

问题现象与初步分析

在开发基于JavaScript的计算器应用时,一个常见的困扰是当用户点击数字按钮后,预期中的数字并没有显示在屏幕上。根据问题描述,开发者注意到在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设置为空字符串''。

立即学习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()方法片段:

Favird No-Code Tools
Favird No-Code Tools

无代码工具的聚合器

下载
    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()方法中,原始代码对所有操作符(减、乘、除)都执行了加法运算。上述完整代码示例中已将这些错误修正为正确的运算逻辑。

关键点与最佳实践

  1. 类状态的初始化: 任何类在其实例化时,都应确保其内部状态变量被正确初始化。这可以防止在后续方法调用中出现undefined或null相关的运行时错误。对于复杂状态,可以封装一个初始化方法(如本例中的clear())并在构造函数中调用。
  2. 仔细检查显示逻辑: 当数据正确处理但界面显示不正确时,应重点检查负责更新UI的逻辑。确保函数返回值被正确使用,并且DOM元素的属性(如innerText)被正确赋值。
  3. 调试技巧: 利用浏览器开发者工具(Console、Sources面板)是定位此类问题的关键。通过设置断点、检查变量值(特别是this对象的状态),可以清晰地看到代码执行流程中变量的变化,从而快速发现问题所在。
  4. 代码审查: 定期进行代码审查,或使用静态代码分析工具,有助于发现潜在的逻辑错误和语法问题,尤其是在团队协作或代码交接时。

通过以上修正,JavaScript计算器将能够正确显示用户输入的数字,并执行预期的计算功能。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
c语言中null和NULL的区别
c语言中null和NULL的区别

c语言中null和NULL的区别是:null是C语言中的一个宏定义,通常用来表示一个空指针,可以用于初始化指针变量,或者在条件语句中判断指针是否为空;NULL是C语言中的一个预定义常量,通常用来表示一个空值,用于表示一个空的指针、空的指针数组或者空的结构体指针。

254

2023.09.22

java中null的用法
java中null的用法

在Java中,null表示一个引用类型的变量不指向任何对象。可以将null赋值给任何引用类型的变量,包括类、接口、数组、字符串等。想了解更多null的相关内容,可以阅读本专题下面的文章。

1089

2024.03.01

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

760

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

221

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1566

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

649

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

1228

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

1184

2024.04.29

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

76

2026.03.11

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.9万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

CSS教程
CSS教程

共754课时 | 42.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号