计算器项目 - 卡住 - JavaScript

3

我在制作这个计算器时遇到了困难......基本上,如果我按等于键,我的计算器可以正常工作(1 + 2 = 3)...但是我希望它即使用户只按操作符也能正常工作,比如1+4/5+2,所以它可以自动计算即使只按操作符。

这是我的代码:

// DOM elements 
const numberButton = document.querySelectorAll('.number');
const operatorButton = document.querySelectorAll('.operator');
const clearButton = document.querySelector('.clear');
const deleteButton = document.querySelector('.delete')
const showResult = document.querySelector('.result');
const currentOperand = document.querySelector('.current-operand');
const previousOperand = document.querySelector('.previous-operand');
const equalsKey = document.querySelector('.equals-key');

currentOperand.textContent = ' ';
previousOperand.textContent = ' ';

// Sum of a, b ... 
function add(a, b) {
  return a + b;
};

// Subtraction of a and b ...
function subtract(a, b) {
  return a - b;
};

// Multiply a, b ... 
function multiply(a, b) {
  return a * b;
};

// Divide a,b ... 
function divide(a, b) {
  return a / b;
};

// Create a new function operate that takes an operator and 2 numbers and then calls one of the above functions on the numbers.
function operate(num1, num2, operator) {
  switch (operator) {
    case "+":
      return add(num1, num2);
    case "-":
      return subtract(num1, num2);
    case "*":
      return multiply(num1, num2);
    case "/":
      return divide(num1, num2);
  }
};

//Create the functions that populate the display when you click the 
//number buttons… you should be storing the ‘display value’ in a variable somewhere 
//for use in the next step.

let storedNumber = '';
let clickedOperator = ''
let firstNumber = '';
let result = '';
currentOperand.textContent = 0;


numberButton.forEach((number) => {
  number.addEventListener('click', function() {
    storedNumber += number.value;
    currentOperand.textContent = storedNumber;
  })
});

operatorButton.forEach((operator => {
  operator.addEventListener('click', function() {

    // save the first number
    firstNumber = storedNumber;

    // get the operator that was clicked
    clickedOperator = operator.textContent;
    previousOperand.textContent = storedNumber + clickedOperator;
    storedNumber = '';

    console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
    console.log(clickedOperator);

  })
}));

equalsKey.addEventListener('click', function() {
  // when equals key is clicked call operate() function
  result = operate(parseFloat(firstNumber), parseFloat(storedNumber), clickedOperator)
  // update content of current operation with result and previous operand with the calculation, make storedNumber = result
  currentOperand.textContent = result;
  previousOperand.textContent = firstNumber + ' ' + clickedOperator + ' ' + storedNumber;
  storedNumber = result;
  console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
})
*,
*::before,
*::after {
  box-sizing: border-box;
  font-weight: normal;
}

body {
  margin: 0;
  padding: 0;
  background: linear-gradient(0.25turn, #3f87a6, #ebf8e1, #f69d3c);
  font-family: sans-serif;
}

.calculator-container {
  display: grid;
  justify-content: center;
  align-content: center;
  min-height: 100vh;
  grid-template-columns: repeat(4, 100px);
  grid-template-rows: minmax(120px, auto) repeat(5, 100px);
}

.two-cols {
  grid-column: span 2;
}

.calculator-container>button {
  cursor: pointer;
  font-size: 2rem;
  border: 1px solid #4289a7;
  outline: none;
  background-color: #f69d3c;
  opacity: 80%;
  border-radius: 5px;
}

.calculator-container>button:hover {
  opacity: 100%;
}

.calculator-display {
  grid-column: 1 / -1;
}

.calculator-display {
  background-color: #efd7a5;
  border: 1px solid #4289a7;
  opacity: 80%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding: 10px;
  padding-top: 39px;
  padding-bottom: 5px;
  border-radius: 5px;
}

.calculator-display .previous-operand {
  font-size: 1.5rem;
}

.calculator-display .current-operand {
  font-size: 2.5rem;
  padding-top: 7px;
}
!
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Calculator Odin Project</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/style.css">
</head>

<body>
  <!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.
        
            Do not worry about wiring up the JS just yet.
            There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
            Add a “clear” button.
        -->

  <div class="calculator-container">
    <div class="calculator-display">
      <div class="previous-operand">3214</div>
      <div class="current-operand">324324</div>
    </div>

    <button class="two-cols clear">AC</button>
    <button class="delete">DEL</button>
    <button class="operator">/</button>
    <button class="number" value="1">1</button>
    <button class="number" value="2">2</button>
    <button class="number" value="3">3</button>
    <button class="operator">*</button>
    <button class="number" value="4">4</button>
    <button class="number" value="5">5</button>
    <button class="number" value="6">6</button>
    <button class="operator">+</button>
    <button class="number" value="7">7</button>
    <button class="number" value="8">8</button>
    <button class="number" value="9">9</button>
    <button class="operator">-</button>
    <button class="number">.</button>
    <button class="number" value="0">0</button>
    <button class="equals-key two-cols result">=</button>

  </div>

  <script src="/index.js" async defer></script>
</body>

</html>


<!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.

    Do not worry about wiring up the JS just yet.
    There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
    Add a “clear” button.
-->

2个回答

5

将计算和显示结果的代码提取到一个独立的函数中。然后可以从equals事件监听器和所有操作符按钮的事件监听器中调用它。

// DOM elements 
const numberButton = document.querySelectorAll('.number');
const operatorButton = document.querySelectorAll('.operator');
const clearButton = document.querySelector('.clear');
const deleteButton = document.querySelector('.delete')
const showResult = document.querySelector('.result');
const currentOperand = document.querySelector('.current-operand');
const previousOperand = document.querySelector('.previous-operand');
const equalsKey = document.querySelector('.equals-key');

currentOperand.textContent = ' ';
previousOperand.textContent = ' ';

// Sum of a, b ... 
function add(a, b) {
  return a + b;
};

// Subtraction of a and b ...
function subtract(a, b) {
  return a - b;
};

// Multiply a, b ... 
function multiply(a, b) {
  return a * b;
};

// Divide a,b ... 
function divide(a, b) {
  return a / b;
};

// Create a new function operate that takes an operator and 2 numbers and then calls one of the above functions on the numbers.
function operate(num1, num2, operator) {
  switch (operator) {
    case "+":
      return add(num1, num2);
    case "-":
      return subtract(num1, num2);
    case "*":
      return multiply(num1, num2);
    case "/":
      return divide(num1, num2);
  }
};

//Create the functions that populate the display when you click the 
//number buttons… you should be storing the ‘display value’ in a variable somewhere 
//for use in the next step.

let storedNumber = '';
let clickedOperator = ''
let firstNumber = '';
let result = '';
currentOperand.textContent = 0;


numberButton.forEach((number) => {
  number.addEventListener('click', function() {
    storedNumber += number.value;
    currentOperand.textContent = storedNumber;
  })
});

operatorButton.forEach((operator => {
  operator.addEventListener('click', function() {
    if (firstNumber && storedNumber) {
      displayResult();
    }
    // save the first number
    firstNumber = storedNumber;

    // get the operator that was clicked
    clickedOperator = operator.textContent;
    previousOperand.textContent = storedNumber + clickedOperator;
    storedNumber = '';

    console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
    console.log(clickedOperator);

  })
}));

equalsKey.addEventListener('click', function() {
  displayResult();
});

function displayResult() {
  result = operate(parseFloat(firstNumber), parseFloat(storedNumber), clickedOperator)
  // update content of current operation with result and previous operand with the calculation, make storedNumber = result
  currentOperand.textContent = result;
  previousOperand.textContent = firstNumber + ' ' + clickedOperator + ' ' + storedNumber;
  storedNumber = result;
  console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber);
}
*,
*::before,
*::after {
  box-sizing: border-box;
  font-weight: normal;
}

body {
  margin: 0;
  padding: 0;
  background: linear-gradient(0.25turn, #3f87a6, #ebf8e1, #f69d3c);
  font-family: sans-serif;
}

.calculator-container {
  display: grid;
  justify-content: center;
  align-content: center;
  min-height: 100vh;
  grid-template-columns: repeat(4, 100px);
  grid-template-rows: minmax(120px, auto) repeat(5, 100px);
}

.two-cols {
  grid-column: span 2;
}

.calculator-container>button {
  cursor: pointer;
  font-size: 2rem;
  border: 1px solid #4289a7;
  outline: none;
  background-color: #f69d3c;
  opacity: 80%;
  border-radius: 5px;
}

.calculator-container>button:hover {
  opacity: 100%;
}

.calculator-display {
  grid-column: 1 / -1;
}

.calculator-display {
  background-color: #efd7a5;
  border: 1px solid #4289a7;
  opacity: 80%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding: 10px;
  padding-top: 39px;
  padding-bottom: 5px;
  border-radius: 5px;
}

.calculator-display .previous-operand {
  font-size: 1.5rem;
}

.calculator-display .current-operand {
  font-size: 2.5rem;
  padding-top: 7px;
}
!
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Calculator Odin Project</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/style.css">
</head>

<body>
  <!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.
        
            Do not worry about wiring up the JS just yet.
            There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
            Add a “clear” button.
        -->

  <div class="calculator-container">
    <div class="calculator-display">
      <div class="previous-operand">3214</div>
      <div class="current-operand">324324</div>
    </div>

    <button class="two-cols clear">AC</button>
    <button class="delete">DEL</button>
    <button class="operator">/</button>
    <button class="number" value="1">1</button>
    <button class="number" value="2">2</button>
    <button class="number" value="3">3</button>
    <button class="operator">*</button>
    <button class="number" value="4">4</button>
    <button class="number" value="5">5</button>
    <button class="number" value="6">6</button>
    <button class="operator">+</button>
    <button class="number" value="7">7</button>
    <button class="number" value="8">8</button>
    <button class="number" value="9">9</button>
    <button class="operator">-</button>
    <button class="number">.</button>
    <button class="number" value="0">0</button>
    <button class="equals-key two-cols result">=</button>

  </div>

  <script src="/index.js" async defer></script>
</body>

</html>


<!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.

    Do not worry about wiring up the JS just yet.
    There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
    Add a “clear” button.
-->


4

每次按下数字键时,简单地运行计算,然后更新显示。

例如,如果您按下“1”,然后是“+”,接着是“2”,计算器将自动显示“3”。

您还可以在单击运算符按钮时让它计算值,尽管这可能没有那么合理。

// DOM elements 
const numberButton = document.querySelectorAll('.number');
const operatorButton = document.querySelectorAll('.operator');
const clearButton = document.querySelector('.clear');
const deleteButton = document.querySelector('.delete')
const showResult = document.querySelector('.result');
const currentOperand = document.querySelector('.current-operand');
const previousOperand = document.querySelector('.previous-operand');
const equalsKey = document.querySelector('.equals-key');

currentOperand.textContent = ' ';
previousOperand.textContent = ' ';

// Sum of a, b ... 
function add(a, b) {
  return a + b;
};

// Subtraction of a and b ...
function subtract(a, b) {
  return a - b;
};

// Multiply a, b ... 
function multiply(a, b) {
  return a * b;
};

// Divide a,b ... 
function divide(a, b) {
  return a / b;
};

// Create a new function operate that takes an operator and 2 numbers and then calls one of the above functions on the numbers.
function operate(num1, num2, operator) {
  switch (operator) {
    case "+":
      return add(num1, num2);
    case "-":
      return subtract(num1, num2);
    case "*":
      return multiply(num1, num2);
    case "/":
      return divide(num1, num2);
  }
};

//Create the functions that populate the display when you click the 
//number buttons… you should be storing the ‘display value’ in a variable somewhere 
//for use in the next step.

let storedNumber = '';
let clickedOperator = ''
let firstNumber = '';
let result = '';
currentOperand.textContent = 0;


numberButton.forEach((number) => {
  number.addEventListener('click', function() {
    storedNumber += number.value;
    previousOperand.textContent += storedNumber;
    calculate();
  })
});

operatorButton.forEach((operator => {
  operator.addEventListener('click', function() {

    // save the first number
    firstNumber = storedNumber;

    // get the operator that was clicked
    clickedOperator = operator.textContent;
    previousOperand.textContent = storedNumber + clickedOperator;
    storedNumber = '';

    console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
    console.log(clickedOperator);

  })
}));

const calculate = () => {
  const result = operate(parseFloat(firstNumber), parseFloat(storedNumber), clickedOperator);

  currentOperand.textContent = result;
  }

equalsKey.addEventListener('click', calculate);
*,
*::before,
*::after {
  box-sizing: border-box;
  font-weight: normal;
}

body {
  margin: 0;
  padding: 0;
  background: linear-gradient(0.25turn, #3f87a6, #ebf8e1, #f69d3c);
  font-family: sans-serif;
}

.calculator-container {
  display: grid;
  justify-content: center;
  align-content: center;
  min-height: 100vh;
  grid-template-columns: repeat(4, 100px);
  grid-template-rows: minmax(120px, auto) repeat(5, 100px);
}

.two-cols {
  grid-column: span 2;
}

.calculator-container>button {
  cursor: pointer;
  font-size: 2rem;
  border: 1px solid #4289a7;
  outline: none;
  background-color: #f69d3c;
  opacity: 80%;
  border-radius: 5px;
}

.calculator-container>button:hover {
  opacity: 100%;
}

.calculator-display {
  grid-column: 1 / -1;
}

.calculator-display {
  background-color: #efd7a5;
  border: 1px solid #4289a7;
  opacity: 80%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding: 10px;
  padding-top: 39px;
  padding-bottom: 5px;
  border-radius: 5px;
}

.calculator-display .previous-operand {
  font-size: 1.5rem;
}

.calculator-display .current-operand {
  font-size: 2.5rem;
  padding-top: 7px;
}
!
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Calculator Odin Project</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/style.css">
</head>

<body>
  <!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.
        
            Do not worry about wiring up the JS just yet.
            There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
            Add a “clear” button.
        -->

  <div class="calculator-container">
    <div class="calculator-display">
      <div class="previous-operand">3214</div>
      <div class="current-operand">324324</div>
    </div>

    <button class="two-cols clear">AC</button>
    <button class="delete">DEL</button>
    <button class="operator">/</button>
    <button class="number" value="1">1</button>
    <button class="number" value="2">2</button>
    <button class="number" value="3">3</button>
    <button class="operator">*</button>
    <button class="number" value="4">4</button>
    <button class="number" value="5">5</button>
    <button class="number" value="6">6</button>
    <button class="operator">+</button>
    <button class="number" value="7">7</button>
    <button class="number" value="8">8</button>
    <button class="number" value="9">9</button>
    <button class="operator">-</button>
    <button class="number">.</button>
    <button class="number" value="0">0</button>
    <button class="equals-key two-cols result">=</button>

  </div>

  <script src="/index.js" async defer></script>
</body>

</html>


<!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.

    Do not worry about wiring up the JS just yet.
    There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
    Add a “clear” button.
-->


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接