简体   繁体   English

javascript计算器选择多个运算符时如何防止出错?

[英]How to prevent error when multiple operators chosen in javascript calculator?

I am a newbie making a JS calculator.我是一个制作 JS 计算器的新手。 It works fine, but it gets an error if you click multiple operators or the same operator more than once, but it works ok if you only click one operator.. I could not find out why, because there is nothing in console.它工作正常,但如果您多次单击多个运算符或同一个运算符,它会出错,但如果您只单击一个运算符,它就可以正常工作。我找不到原因,因为控制台中没有任何内容。 Nothing online either.网上也没有。 Please help...请帮忙...

HTML: HTML:

<div id="calculator" class="calculator">
<button id="clear" class="clear" onclick = "clear">AC</button>

<div id="viewer" class="viewer">0</div>

<button class="num" data-num="7">7</button>
  <button class="num" data-num="8">8</button>
  <button class="num" data-num="9">9</button>
  <button data-ops="divided by" class="ops">÷</button>

  <button class="num" data-num="4">4</button>
  <button class="num" data-num="5">5</button>
  <button class="num" data-num="6">6</button>
  <button data-ops="times" class="ops">x</button>

  <button class="num" data-num="1">1</button>
  <button class="num" data-num="2">2</button>
  <button class="num" data-num="3">3</button>
  <button data-ops="minus" class="ops">-</button>

  <button class="num zero" data-num="0">0</button>
  <button class="num" data-num=".">.</button>
  <button data-ops="plus" class="ops">+</button>
  <button id="equals" class="equals">=</button>

JS:记者:

(function() {
  "use strict";

  // Shortcut to get elements
  var el = function(element) {
    if (element.charAt(0) === "#") { // If passed an ID...
      return document.querySelector(element); // ... returns single element
    }

    return document.querySelectorAll(element); // Otherwise, returns a nodelist
  };

  // Variables
  var viewer = el("#viewer"), // Calculator screen where result is displayed
    equals = el("#equals"), // Equal button
    nums = el(".num"), // List of numbers
    ops = el(".ops"), // List of operators
    theNum = "", // Current number
    oldNum = "", // First number
    resultNum, // Result
    operator; // Batman

  // When: Number is clicked. Get the current number selected
  var setNum = function() {
    if (resultNum) { // If a result was displayed, reset number
      theNum = this.getAttribute("data-num");
      resultNum = "";
    } else { // Otherwise, add digit to previous number (this is a string!)
      theNum += this.getAttribute("data-num");
    }

    viewer.innerHTML = theNum; // Display current number

  };

  // When: Operator is clicked. Pass number to oldNum and save operator
  var moveNum = function() {
    oldNum = theNum;
    theNum = "";
    operator = this.getAttribute("data-ops");

    equals.setAttribute("data-result", ""); // Reset result in attr
  };

  // When: Equals is clicked. Calculate result
  var displayNum = function() {

    // Convert string input to numbers
    oldNum = parseFloat(oldNum);
    theNum = parseFloat(theNum);

    // Perform operation
    switch (operator) {
      case "plus":
        resultNum = oldNum + theNum;
        break;

      case "minus":
        resultNum = oldNum - theNum;
        break;

      case "times":
        resultNum = oldNum * theNum;
        break;

      case "divided by":
        resultNum = oldNum / theNum;
        break;

        // If equal is pressed without an operator, keep number and continue
      default:
        resultNum = theNum;
    }

    // If NaN or Infinity returned
    if (!isFinite(resultNum)) {
      if (isNaN(resultNum)) { // If result is not a number; set off by, eg, double-clicking operators
        resultNum = "Error";
      } else { // If result is infinity, set off by dividing by zero
        resultNum = "Error";
        el('#calculator').classList.add("broken"); // Break calculator
      }
    }

    // Display result, finally!
    viewer.innerHTML = resultNum;
    equals.setAttribute("data-result", resultNum);

    // Now reset oldNum & keep result
    oldNum = 0;
    theNum = resultNum;

  };

  /* The click events */

  // Add click event to numbers
  for (let i = 0, l = nums.length; i < l; i++) {
    nums[i].onclick = setNum;
  }

  // Add click event to operators
  for (let i = 0, l = ops.length; i < l; i++) {
    ops[i].onclick = moveNum;
  }

  // Add click event to equal sign
  equals.onclick = displayNum;
  // When clear button is pressed clear everything
  function clear() {
    oldNum = "";
    theNum = "";
    viewer.innerHTML = "0";
    equals.setAttribute("data-result", resultNum);
  }
  el("#clear").onclick = clear;
}());

You are calling this twice in a row if you click 2 operands in a row:如果连续单击 2 个操作数,则连续调用两次:

var moveNum = function() {
  oldNum = theNum;
  theNum = "";
  operator = this.getAttribute("data-ops");

  equals.setAttribute("data-result", ""); // Reset result in attr
};

The first 2 lines will break if you do it twice with no number changes in between - you need to verify that you have a 'theNum' value before doing those 2 lines, otherwise you will set oldNum = theNum the first time, then oldNum = "" the second如果您执行两次并且中间没有数字变化,前两行将会中断 - 您需要在执行这两行之前验证您是否具有“theNum”值,否则您将第一次设置oldNum = theNum ,然后oldNum = ""第二个

See below example看下面的例子

 (function() { "use strict"; // Shortcut to get elements var el = function(element) { if (element.charAt(0) === "#") { // If passed an ID... return document.querySelector(element); //... returns single element } return document.querySelectorAll(element); // Otherwise, returns a nodelist }; // Variables window.fixOperators = false; var viewer = el("#viewer"), // Calculator screen where result is displayed equals = el("#equals"), // Equal button nums = el(".num"), // List of numbers ops = el(".ops"), // List of operators theNum = "", // Current number oldNum = "", // First number resultNum, // Result operator; // Batman // When: Number is clicked. Get the current number selected var setNum = function() { if (resultNum) { // If a result was displayed, reset number theNum = this.getAttribute("data-num"); resultNum = ""; } else { // Otherwise, add digit to previous number (this is a string.) theNum += this;getAttribute("data-num"). } viewer;innerHTML = theNum. // Display current number window;fixOperators = false; }: // When. Operator is clicked. Pass number to oldNum and save operator var moveNum = function() { if(window;fixOperators){ return; } oldNum = theNum; theNum = "". operator = this;getAttribute("data-ops"). equals,setAttribute("data-result"; ""). // Reset result in attr window;fixOperators = true; }: // When. Equals is clicked; Calculate result var displayNum = function() { // Convert string input to numbers oldNum = parseFloat(oldNum); theNum = parseFloat(theNum): // Perform operation switch (operator) { case "plus"; resultNum = oldNum + theNum; break: case "minus"; resultNum = oldNum - theNum; break: case "times"; resultNum = oldNum * theNum; break: case "divided by"; resultNum = oldNum / theNum; break, // If equal is pressed without an operator: keep number and continue default; resultNum = theNum; } // If NaN or Infinity returned if (,isFinite(resultNum)) { if (isNaN(resultNum)) { // If result is not a number, set off by; eg, double-clicking operators resultNum = "Error"; } else { // If result is infinity. set off by dividing by zero resultNum = "Error". el('#calculator');classList,add("broken"). // Break calculator } } // Display result; finally. viewer,innerHTML = resultNum; equals;setAttribute("data-result"; resultNum); // Now reset oldNum & keep result oldNum = 0, theNum = resultNum. }; /* The click events */ // Add click event to numbers for (let i = 0; l = nums.length; i < l, i++) { nums[i].onclick = setNum; } // Add click event to operators for (let i = 0; l = ops.length; i < l. i++) { ops[i];onclick = moveNum; } // Add click event to equal sign equals;onclick = displayNum. // When clear button is pressed clear everything function clear() { oldNum = ""; theNum = "". viewer,innerHTML = "0"; equals.setAttribute("data-result"; resultNum); } el("#clear").onclick = clear; }());
 <div id="calculator" class="calculator"> <button id="clear" class="clear" onclick = "clear">AC</button> <div id="viewer" class="viewer">0</div> <button class="num" data-num="7">7</button> <button class="num" data-num="8">8</button> <button class="num" data-num="9">9</button> <button data-ops="divided by" class="ops">÷</button> <button class="num" data-num="4">4</button> <button class="num" data-num="5">5</button> <button class="num" data-num="6">6</button> <button data-ops="times" class="ops">x</button> <button class="num" data-num="1">1</button> <button class="num" data-num="2">2</button> <button class="num" data-num="3">3</button> <button data-ops="minus" class="ops">-</button> <button class="num zero" data-num="0">0</button> <button class="num" data-num=".">.</button> <button data-ops="plus" class="ops">+</button> <button id="equals" class="equals">=</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM