首页 > 解决方案 > 带有javascript的简单计算器,它的功能计算器不适用

问题描述

我是 Javascript 新手,所以这可能是一个简单的解决方法,但我无法弄清楚。我正在使用 HTML、CSS 和 Javascript 制作计算器,而我几乎只知道声明、if/else 语句、for/while 循环以及 CSS 和 HTML 的一些基本元素。

这是我用于计算器的 javascript 代码。

var firstNum, operator, previousKey, previousNum;

const calculator = document.querySelector('.calculator'); 
const buttons = calculator.querySelector('.calculator__buttons'); 
const display = document.querySelector('.calculator__display');


function calculate(n1, operator, n2) {
  let result = '';
  
  if(operator === '+'){
    result = n1 + n2;
  }else if(operator === '-'){
    result = n1 - n2;
  }else if(operator === '*'){
    result = n1 * n2;
  }else if(operator === '/'){
    result = n1 / n2;
  }
   return result;
}


buttons.addEventListener('click', function (event) {


  const target = event.target; 
  const action = target.classList[0];
  const buttonContent = target.textContent; 
  if (target.matches('button')) {
    
    
    let firstNum = 0;
    if (action === 'number') {
      
      if (display.textContent > 0 ) {
        display.textContent += buttonContent //
      }
      else {display.textContent = buttonContent}
      
      //display.textContent = buttonContent
      console.log('number1 ' + buttonContent + ' button1');
      previousKey = 'number';
    }

    if (action === 'operator') {
      console.log('operator1 ' + buttonContent + ' button1');
      operator = buttonContent;
      firstNum = display.textContent
      //console.log(firstNum) 
      return firstNum
      previousKey = 'operator';
    }

    if (action === 'decimal') {
      // console.log('deciaml1');
      previousKey = 'decimal';
    }

    if (action === 'clear') {
      display.textContent = '0'
      console.log('clear1');
      previousKey = 'clear';
    }

    if (action === 'calculate') {
      console.log('caculate1');
      display.textContent = calculate(firstNum, operator, display.textContent)
      previousKey = 'calculate';
    }
  }
});

虽然我将上面的算术运算设置为函数 calculate(n1, operator, n2)

我的计算器//这是它的样子。

5-9 的结果为 -59。如果我能得到一些帮助,我将不胜感激。先感谢您。

标签: javascripthtmlcalculator

解决方案


问题是您正在将字符串发送到计算函数。因此,您应该在代码中将字符串 textContent 显式转换为整数值:

if (action === 'calculate') {
      console.log('caculate1');
      display.textContent = calculate(parseInt(firstNum,10), operator, parseInt(display.textContent,10))
      previousKey = 'calculate';
}

推荐阅读