【问题标题】:JS issue then creating a calculator and being able to type in multiple numbersJS 问题然后创建一个计算器并能够输入多个数字
【发布时间】:2020-03-20 21:00:07
【问题描述】:

我一直在关注创建计算器的视频教程,我还没有完成程序,但我应该能够在计算器上输入多个数字然后按下按钮(无需任何加法、减法、乘法或除法,但是)但是我收到错误消息,我不确定如何修复。有人可以帮忙吗?

Calculator link

【问题讨论】:

    标签: javascript calculator


    【解决方案1】:

    Dan,您应该经常查看错误并尝试找出发生了什么。你的错误说:Uncaught TypeError: Cannot read property 'toString' of undefined Line: 22

    这意味着,'嘿,你尝试调用 toString 的东西实际上不是对象或值,而是 undefined

    现在你应该转到第 22 行,即:

    this.currentOperand = this.currentOperand.toString() + number.toString();

    并尝试找出问题所在 - 通常您使用调试器,或者只是使用 console.log,如下所示:

    appendNumber(number) {
      console.log('Current operand: ', this.currentOperand);
      console.log('Number: ', number);
    
      this.currentOperand = this.currentOperand.toString() + number.toString();
    }
    

    在您的情况下 - this.currentOperandundefined,因为您从未初始化它(它在 calculator.clear 中分配,但您从未调用它)。

    此修复程序将使您能够继续:

    const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement);
    calculator.clear()
    

    【讨论】:

    • Alex Brohshtut 谢谢,它解决了这个问题!
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2022-12-11
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多