Home > Enterprise >  I am trying to push a value onto an array with .push(), but it stops pushing values once the array l
I am trying to push a value onto an array with .push(), but it stops pushing values once the array l

Time:09-12

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 >Calculator</h1>
    <div >
        <div >
            <div >This will print result</div>
            <button >Clear</button>
            <button > </button>
            <button >-</button>
            <button >x</button>
            <button >/</button>
            <button >=</button>
            <button >1</button>
            <button >2</button>
            <button >3</button>
            <button >4</button>
            <button >5</button>
            <button >6</button>
            <button >7</button>
            <button >8</button>
            <button >9</button>
            <button >0</button>
            <button >.</button>
        </div>
    </div>
</body>
</html>

CodePudding user response:

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)

  • Related