我使用了一个简单的Java脚本计算器,使用的是HTML和css.但是,当我单击某个按钮时,特定值并未按预期显示.这段代码出了什么问题,我该如何修复它?我是JS的新手,这个问题是从JS,this.currentOperand = this.currentOperand.toString() + number.toString()appendNumber函数中的这行代码开始的

注意-代码不是我的

class Calculator {
    constructor(previousOperandTextElement, currentOperandTextElement) { 
        this.previousOperandTextElement = previousOperandTextElement;
        this.currentOperandTextElement = currentOperandTextElement;
    }

    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() {
        this.currentOperandTextElement.innerText = this.currentOperand
            this.getDisplayNumber(this.currentOperand)
        if (this.operation != null) {
            this.previousOperandTextElement.innerText = this.previousOperand
                `${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()
}) 
*, *::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;
}
<!DOCTYPE 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>

推荐答案

当您拨打appendNumber()时会收到Cannot read properties of undefined错误,因为this.currentOperandundefined.你可以通过在Calculatorconstructor()的基础上增加this.clear()来解决这个问题.

Javascript相关问答推荐

自定义帖子类型帖子未显示在网站上

如何在非独立组件中使用独立组件?

如何使用React渲染器放置根dis?

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

有什么(最佳)方法可以从模块中获取脚本模块的多姆元素吗?

从mat—country—select获取整个Country数组

将2D数组转换为图形

为什么我的列表直到下一次提交才更新值/onChange

google docs boldText直到按行执行应用脚本错误

无法检测卡片重叠状态的问题

如何在 cypress 中使用静态嵌套循环

使用POST请求时,Req.Body为空

当id匹配时对属性值求和并使用JavaScript返回结果

使用Nuxt Apollo在Piniastore 中获取产品细节

Next.js中的服务器端组件列表筛选

在Odoo中如何以编程方式在POS中添加产品

为列表中的项目设置动画

Angel Auth Guard-用户只有在未登录时才能访问登录页面,只有在登录时才能访问其他页面

无法向甜甜圈图表上的ChartJSImage添加可见标签

我如何才能让p5.js在不使用实例模式的情况下工作?