Проблема с написанием калькулятора JS
Доброго времени суток!
Помогите разобраться, я только начал изучать front. Делал калькулятор, вроде работает, но есть нюансы: не могу сделать что бы он считал вот так, например: 5 + 4 + 4+ 3 и тд. Он при нажатии на '=' добавляет только последнюю цифру.
сам код:
<script>
let firstNum = '' // первое число
let secondNum = '' // второе число
let arithmetic = '' // арифметика
let stop = false
let digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']
let arithmeticGo = ['-', '+', '/', '*']
let outScreen = document.querySelector('.calculator_screen p')
function clearScreen() {
// очистка
firstNum = ''
secondNum = ''
arithmetic = ''
stop = false
outScreen.textContent = 0
}
// AC
document.querySelector('.ac').onclick = clearScreen
document.querySelector('.buttons').onclick = (event) => {
if (!event.target.classList.contains('btn')) return
if (event.target.classList.contains('ac')) return
outScreen.textContent = ''
// беру кнопку которую нажимаю
var key = event.target.textContent
// условие, если нажат арифметический знак
if (digits.includes(key)) {
if (secondNum == '' && arithmetic == '') {
firstNum += key
outScreen.textContent = firstNum
} else if (firstNum !== '' && secondNum !== '' && stop) {
secondNum = key
stop = false
outScreen.textContent = secondNum
} else {
secondNum += key
outScreen.textContent = secondNum
}
// console.log(firstNum, secondNum, arithmetic)
return
}
// если нажата кнопка / * - +
if (arithmeticGo.includes(key)) {
arithmetic = key
if (key) {
outScreen.textContent = firstNum
}
// outScreen.textContent = arithmetic // убираем знак
// console.log(arithmetic) // проверяем
return
}
if (key === '=') {
if (secondNum === '') secondNum = firstNum
switch (arithmetic) {
case '+':
firstNum = +firstNum + +secondNum // избегаем конкатенации
break
case '-':
firstNum = firstNum - secondNum
break
case '*':
firstNum = firstNum * secondNum
break
case '/':
if (secondNum === '0') {
outScreen.textContent = 'На ноль делить нельзя!'
firstNum = ''
secondNum = ''
arithmetic = ''
return
}
firstNum = firstNum / secondNum
break
}
stop = true
outScreen.textContent = firstNum
// console.log(firstNum, secondNum, arithmetic)
}
}
</script>