JS 问题然后创建计算器并能够输入多个数字

JS issue then creating a calculator and being able to type in multiple numbers

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

Calculator link

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()