【问题标题】:Calculator project - stuck - javascript计算器项目 - 卡住 - javascript
【发布时间】:2020-11-13 10:15:39
【问题描述】:

我坚持让这个计算器工作......所以如果我按下等于键(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.
-->

【问题讨论】:

    标签: javascript project calculator


    【解决方案1】:

    将计算和显示结果的代码提取到一个单独的函数中。然后,您可以从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.
    -->

    【讨论】:

      【解决方案2】:

      每次按下数字时只需运行计算,然后更新视图。

      例如,如果您按“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.
      -->

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-22
        • 2016-04-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多