![](/img/trans.png)
[英]Uncaught TypeError: Cannot read property 'toString' of undefined
[英]TypeError 'Cannot read property/undefined ' when using toString property
我目前正在尝试编写一个基本的计算器,但我撞到了一堵墙。 我试图在 output 上显示多个数字,我确实在 clear() 中将 currentOperand 声明为空变量。 在 appendNumber() 中,如果我将 this.currentOperand 设置为等于数字,它将显示但仅显示单个数字。 建议将 this.currentOperand 中的字符串值返回给 output 多个数字。
JS代码
constructor(previousoperandTextElement, currentoperandTextElement){
this.previousoperandTextElement = previousoperandTextElement
this.currentoperandTextElement = currentoperandTextElement
}
clear(){
this.currentOperand = "";
this.previousOperand = "";
this.operation = undefined;
}
delete(){
}
appendNumber(number){
if(number === "." && this.currentOperand.includes('.')) return
this.currentOperand = this.currentOperand.toString() + number.toString()
console.log(number);
}
chooseOperation(operation){
}
compute(){
}
updateDisplay(){
this.currentoperandTextElement.innerText = this.currentOperand;
}
}
const numberButtons = document.querySelectorAll("[data-number]")
const operationButtons = document.querySelectorAll("[data-operation]")
const deleteButton = document.querySelector("[data-delete]")
const all_clearButton = document.querySelector("[data-all-clear]")
const equalsButton = document.querySelector("[data-equals]")
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();
})
})
当前操作数不是字符串吗? 因此,您无需将其转换为字符串。
所以
this.currentOperand = this.currentOperand + number.toString()
您还可以在转换为字符串之前先在控制台中检查类型,以确定您要转换的内容:
console.log(typeof this.currentOperand);
如果您使用 Typescript,这些事情也会更加清晰。
编辑回顾它,它看起来也像变量number
是一个字符串。 如果它将严格等于“。” - 您正在尝试转换包含.
成一个字符串,它已经是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.