简体   繁体   中英

Why does my Javascript calculator multiply the answer by 2 when pressing an operator following an equals press?

I am working my way through The Odin Project and I'm currently stuck on the "Calculator" project.

For the most part, considering my current Javascript knowledge, I am happy with how it works. However; after outputting the result of a calculation by pressing the equals button, if I then press any of the mathematical operators if will then immediately multiply the displayed value by 2 and I can not figure out why.

The calculator can be found here: https://nortski78.github.io/calculator/

To reproduce the bug, enter 5 + 5 = + (that will display 20)

The parts of my code where I believe the problem lies is:

operatorButtons.forEach((operatorButton) => {
    operatorButton.addEventListener('click', (event) => {
        setOperand(getDisplayValue());        
        setOperator(event.target.textContent);  
        clear = true;
    })
})

btnEquals.addEventListener('click', (event) => {
    setOperand(getDisplayValue());
    operate(operator, firstOperand, secondOperand);
    clear = true;
})

function setOperand(operand){

    operand = parseFloat(operand);

    if(firstOperand === null) { firstOperand = operand; }
    else { 
        secondOperand = operand;
        clear = true;
        updateDisplay(operate(operator, firstOperand, secondOperand));
        firstOperand = getDisplayValue();
    }
}

function setOperator(digit){

    if(digit != "="){
        operator = digit;
    }
}

function operate(operator, num1, num2){

    switch(operator){
        case "+":
            return add(num1, num2);
            break;
        case "-":
            return subtract(num1, num2);
            break;
        case "*":
            return multiply(num1, num2);
            break;
        case "/":
            return divide(num1, num2);
            break;
    }
}

Clicking + calls setOperand . In there if(firstOperand === null) won't be true, you already assigned a value to that variable before (when you processed the previous + button click), and it never gets “nulled” again anywhere.

So this proceeds with assigning secondOperand , and then it calls operate wrapped in updateDisplay .

So after pressing = , you have to reset your first operand, so that when it goes through setOperand again, it will assign a new first operand first, and only perform the calculation & display update on the second operand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM