简体   繁体   中英

I am trying to push a value onto an array with .push(), but it stops pushing values once the array length reaches two

I'm trying to create a javascript calculator for The Odin Project. I finally felt like I was making a bit of progress, after headbutting my keyboard for hours, and then this weird bug arose.

In the function where I add event listeners to the operator buttons, I am trying to push the current operator (the last one which was clicked) on to an array which keeps track of the operator buttons which have been clicked ('newOperators.push(e.target.innerText)').

If I spam the operator button, it pushes on to the array just fine. But when I am trying to chain together a series of operations, the newOperators.push() method seems to quit after the array length reaches two.

To test, I added another dummy array and pushed letters onto it on using another push() method, which I put on the line above newOperators.push(), and that seems to work just fine. I've tried switching newOperators.push() to newOperators.unshift() and that has the same issue.

Losing my mind here, any help would be much appreciated!

Javascript:

let display = document.querySelector('.display');
let title = document.querySelector('.title');


let plus = document.querySelector('.plus');
let minus = document.querySelector('.minus');
let times = document.querySelector('.multiply');
let divide = document.querySelector('.divide');
let equal = document.querySelector('.equal');
let period = document.querySelector('.period');

let one = document.querySelector('.one');
let two = document.querySelector('.two');
let three = document.querySelector('.three');
let four = document.querySelector('.four');
let five = document.querySelector('.five');
let six = document.querySelector('.six');
let seven = document.querySelector('.seven');
let eight = document.querySelector('.eight');
let nine = document.querySelector('.nine');
let nought = document.querySelector('.nought');

let buttons = document.querySelectorAll('button');
let operators = document.querySelectorAll('.operator');
let numbers = document.querySelectorAll('.number');


let currentCalc = [];

let currentOp = '';



let firstNumber = 0;
let secondNumber = 0;
let thirdNumber = 0;

let firstStash = 0;
let secondStash = 0;
let total = 0;

let calculated = false;
let newOperators = [];

const add = function(a,b) {
    return a + b;
};

const subtract = function(a,b) {
    return a - b;
};

const multiply = function(a,b) {
    return a * b
};
const division = function(a,b) {
    return a / b
};




function operate(fnum,snum, op) {
    if(op === '+') {
        let sum = add(fnum,snum);
        return sum;
    } else if(op === '-') {
        let sum = subtract(fnum,snum);
        return sum;
    } else if(op === 'x') {
        let sum = multiply(fnum,snum);
        return sum;
    } else if(op === '/') {
        let sum = division(fnum,snum);
        return sum;
    }
}

let fNumArr = [];
let sNumArr = [];
let tNumArr = [];

numbers.forEach((e) => {
    e.addEventListener('click', (e) => {
            console.log('numberFunc', newOperators)
            if(newOperators.length < 1) {
                fNumArr.push(e.target.innerText)
                firstNumber = parseInt(fNumArr.join(''));
                console.log('first',firstNumber);
                display.textContent = firstNumber;
            } else if( newOperators.length = 1) {
                
                sNumArr.push(e.target.innerText);
                secondNumber = parseInt(sNumArr.join(''));
                console.log('second',secondNumber);
                display.textContent = secondNumber;
                
            } else if(newOperators.length > 1) {

            tNumArr.push(e.target.innerText);
            thirdNumber = parseInt(tNumArr.join(''));
            console.log('third',thirdNumber);
            display.textContent = thirdNumber;

        }  
    })
})

operators.forEach((e) => {
    e.addEventListener('click', (e) => {
        console.log(currentOp)
        newOperators.push(e.target.innerText);
        console.log('topOfOp',newOperators)
        display.innerText = '';
            if(newOperators.length === 1) {
   
            } else if(newOperators.length === 2) {
                console.log(operate(firstNumber,secondNumber,newOperators[1]));
                total = operate(firstNumber,secondNumber,newOperators[1]);
    
                display.innerText = total;
                firstNumber = total;
                secondNumber = 0;
                fNumArr = [];
                fNumArr.push(total)
                sNumArr = [];
             
            }
    })
})

HTML:

<!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>Caculator</title>
    <link rel="stylesheet" href="styles.css">
    <script src="./app.js" defer></script>
</head>
<body>
    <h1 class="title">Calculator</h1>
    <div class="container">
        <div class="calculator">
            <div class="display">This will print result</div>
            <button class="clear">Clear</button>
            <button class="plus operator">+</button>
            <button class="minus operator">-</button>
            <button class="multiply operator">x</button>
            <button class="divide operator">/</button>
            <button class="equal ">=</button>
            <button class="one number">1</button>
            <button class="two number">2</button>
            <button class="three number">3</button>
            <button class="four number">4</button>
            <button class="five number">5</button>
            <button class="six number">6</button>
            <button class="seven number">7</button>
            <button class="eight number">8</button>
            <button class="nine number">9</button>
            <button class="nought number">0</button>
            <button class="period number">.</button>
        </div>
    </div>
</body>
</html>

In your numbers.forEach loop you made the mistake of: if( newOperators.length = 1) You should fix that. Also, a little advice as you are starting out (I am also starting out WebDev):

  • You should name your variables clearly even of they are too long.

  • Refractor your code into functions and files for example make it so you pass in a callback to your event listeners and get rid of repetitive code. Remember keep it DRY (Don't Repeat Your code)

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