我的计算器需要帮助.我不知道如何把几次行动结合起来.

我的计算器是这样工作的:

  1. 从用户那里获取一个数字.存储到数组中.
  2. 如果用户一直按数字按钮,则继续将其按入array.
  3. 当用户点击操作员时,将其存储到currentOperator.将数组解析为整数.将结果存储到firstNumber.然后是空array.
  4. 从用户处获取另一个号码,存储到数组,重复步骤2.
  5. 当用户点击equals按钮时,再次将数组解析为整数.将结果存储到secondNumber并调用函数calculate()

const operator = document.querySelectorAll('.operator');
const equalsKey = document.getElementById('equalsKey');
const display = document.getElementById('result');
const numbers = document.querySelectorAll('.number');
const operators = document.querySelectorAll('.operator');
const clear = document.getElementById('clear');

let firstNumber;
let currentOperator;
let secondNumber;
let tempArray = [];

numbers.forEach((number) => {
    number.addEventListener('click', (e) => {
        tempArray.push(e.target.value); // store value to temparray
        console.log(tempArray);
        display.innerHTML = Number(tempArray.join("")); // display number from array
    });
});

operators.forEach((operator) => {
    operator.addEventListener('click', (e) => {
        currentOperator = e.target.value; // store current operator
        console.log(currentOperator);
        firstNumber = Number(tempArray.join("")); // parse array to integers
        console.log(firstNumber);
        tempArray = []; // empty array
    });
});

clear.addEventListener('click', function () {
    display.textContent = '0';
})

function calculate() {
    secondNumber = Number(tempArray.join(""));
    let result = operate(parseFloat(firstNumber), parseFloat(secondNumber), currentOperator);
    display.textContent = result;
}


function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

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

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

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);
    }
};

equalsKey.addEventListener('click', calculate);

https://codepen.io/alcatel1962/pen/LYONKKW

我不知道在try 将几个操作组合在一起时如何思考.

推荐答案

this existing code-pen solution的基础上改进,创建了以下内容.

要执行/查看下面的代码片段,请切换到FULL PAGE.

Code Snippet

const operator = document.querySelectorAll('.operator');
const equalsKey = document.getElementById('equalsKey');
const display = document.getElementById('result');
const numbers = document.querySelectorAll('.number');
const operators = document.querySelectorAll('.operator');
const clear = document.getElementById('clear');
const deci = document.getElementById('deci');
// to view debug info, change class 'hideDebug' display-style in CSS
const debug = document.getElementById('debug');

deci.addEventListener('click', () => alert('decimals not yet added...'));
// a temp array to hold input characters
let cache = [];

// a closure to handle creating, manipulating the parse-tree
function parser() {
  // a tree-structure to use for storing & parsing operators, operands.
  const myTree = { root: null, left: null, right: null };
  
  // reset tree to original state
  const reset = (mt) => {
    mt.root = null; mt.left = null; mt.right = null;
  };
  
  // add a new operand or operator into the proper location
  // uses BODMAS (also called PEDMAS, PEMDAS, BOMDAS, etc)
  // basically division-multiplication takes priority over addition-subtraction
  const add = (el, type, nt) => {
    if (type === 'operand') {
      if (nt.left === null) nt.left = +el;
      else if (nt.right === null) nt.right = +el;
      else add(el, type, nt.right);
    } else {
      if (nt.root === null) nt.root = el;
      else if ('+-'.includes(nt.root) && '/*'.includes(el)) {
        // if current operator is / or * and previous is + or -
        // structure tree so that the / or * takes precedence
        const t = structuredClone(nt.right);
        nt.right = { root: el, left: t, right: null };
      } else {
        // for all other cases left side calculation takes precedence
        const t = structuredClone(nt);
        nt.left = t;
        nt.root = el;
        nt.right = null;
      };
    };
  };
  
  // helper method to quickly compute simple operations
  const compute = (op1, op, op2) => {
    switch (op) {
      case '+': return op1 + op2;
      case '-': return op1 - op2;
      case '*': return op1 * op2;
      case '/': return op1 / op2;
    }
  };
  
  // recursive method to evaluate the parse-tree
  const evaluate = (et) => (
    compute(
      Number.isFinite(et.left) ? et.left : evaluate(et.left),
      et.root,
      Number.isFinite(et.right) ? et.right : evaluate(et.right)
    )
  );
  
  // return object with relevant methods
  return {
    isEmpty: () => myTree.root === null,
    addToTree: (el, type = 'operand') => {
      add(el, type, myTree);
    },
    showTree: () => (JSON.stringify(myTree)),
    clearTree: () => {reset(myTree)},
    calculate: () => evaluate(myTree)
  };
};
const myParser = parser();

// handle clear button click
clear.addEventListener('click', function () {
    display.textContent = '0';
    myParser.clearTree();
    debug.innerHTML = myParser.showTree();
    cache = [];
});

// for each number clicked,
// cache the value, and update display
numbers.forEach(el => {
  el.addEventListener('click', (ev) => {
    if (cache.length === 0 && myParser.isEmpty()) display.innerHTML = ev.target.value;
    else display.innerHTML += ev.target.value;
    cache.push(ev.target.value);
  });
});

// for each operator clicked,
// process existing cache and operator into parse-tree
operator.forEach(el => {
  el.addEventListener('click', (ev) => {
    if (cache.length > 0 || ev.target.value === '-') {
      if (cache.length === 0) {  // negative number as operand-1
        display.innerHTML = '0-';
        cache.push(0);
      } else if (!('+-*/'.includes(cache.slice(-1)))) display.innerHTML += ev.target.value;
      myParser.addToTree(cache.join(''));
      cache = [];
      myParser.addToTree(ev.target.value, 'operator');
      debug.innerHTML = myParser.showTree();
    }
  });
});

// calculate method
// add last operand to parse-tree, clear cache
// obtain the calculated-result, display & cache it
// finally, clear the parse-tree
const calculate = () => {
  myParser.addToTree(cache.join(''));
  cache = [];
  debug.innerHTML = myParser.showTree();
  const calcResult =  myParser.calculate();
  display.innerHTML = calcResult;
  cache.push(calcResult);
  myParser.clearTree();
};

equalsKey.addEventListener('click', calculate);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 10px;
}

body {
  font-family: "Open Sans", sans-serif;
}

p {
  font-size: 16px;
  line-height: 1.5;
}

img {
  width: 100%;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

.box {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.calc {
  width: 300px;
  height: 350px;
  margin: 0 auto;
  background-color: #ccc;
  padding: 15px;
  border-radius: 3px;
  position: relative;
}

.result {
  color: rgb(68, 66, 66);
  background-color: #fff;
  height: 45px;
  width: 70%;
  border-radius: 3px;
  margin-bottom: 5px;
  border: 2px solid grey;
  padding: 10px;
  overflow: hidden;
}

.clear {
  width: 20%;
  height: 45px;
  padding: 10px;
  position: absolute;
  right: 20px;
  top: 5px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 16px;
}


.keys {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 5px;
  font-size: 16px;
}

.keys button {
  list-style: none;
  width: 50px;
  background-color: #fff;
  margin: 10px 5px;
  padding: 10px;
  /* border-bottom: 1px solid #dadedc; */
  border-radius: 3px;
  color: rgb(68, 66, 66);
  text-align: center;
  cursor: pointer;
  transition: all 0.1s;
}

.keys button:hover {
  background-color: #dadedc;
  color: #000;
}

.keys .equals {
  background-color: blue;
  color: #fff;
}

.hideDebug { display: none; }
<div class='hideDebug' id='debug'>aa</div>
<section>
        <div class="container box">
            <div class="calc">
                <div class="result">
                    <p id="result">0</p>
                </div>
                <button class="clear" id="clear">C</button>

                <ul class="keys">
                    <button class="number" value="1">1</button>
                    <button class="number" value="2">2</button>
                    <button class="number" value="3">3</button>
                    <button class="operator" value="+">+</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" value="-">-</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" value="*">*</button>
                    <button class="number" value="0">0</button>
                    <button id='deci' class="decimal" value=".">.</button>
                    <button class="equals" id="equalsKey" value="=">=</button>
                    <button class="operator" value="/">÷</button>
                </ul>
            </div>
        </div>
    </section>

Explanation

在上述代码段中内联添加了详细注释

Javascript相关问答推荐

如何制作删除按钮以从列表中删除该项目所属的项目?

如何提取Cypress中文本

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

使用JavaScript单击上一个或下一个特定按钮创建卡滑动器以滑动单个卡

D3多线图显示1线而不是3线

Cookie中未保存会话数据

WebRTC关闭navigator. getUserMedia正确

在拖放时阻止文件打开

PDF工具包阿拉伯字体的反转数字

如何在每次单击按钮时重新加载HighChart/设置HighChart动画?

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

Web Crypto API解密失败,RSA-OAEP

在使用REACT更改了CSS类之后,无法更改CSS样式

如何使用TypeScrip设置唯一属性?

当我在Reaction中创建一个输入列表时,我的输入行为异常

将异步回调转换为异步生成器模式

打字脚本中方括号符号属性访问和拾取实用程序的区别

使用jQuery find()获取元素的属性

react -原生向量-图标笔划宽度

KeyboardEvent:检测到键具有打印的表示形式