类型使用 toString 属性时'Cannot read property/undefined '错误



我目前正试图编写一个基本的计算器,但我遇到了瓶颈。我试图在输出上显示多个数字,我确实在clear()中将currentOperand声明为空变量。在appendNumber()中,如果我设置this。currentOperand等于它将显示的数字,但只是个位数。建议在this中返回一个字符串值。currentOperand输出多个数字

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是一个字符串。如果它严格等于"。"-您正在尝试将包含.的字符串转换为字符串,而它已经是字符串了。

相关内容

最新更新