首页 > 解决方案 > 需要有人帮助我处理数组中的 javascript 数组

问题描述

问题是我正在做一个计算器。我希望当用户输入一个或多个数字时,程序将它们推送到数组 tab1 中,并且只要他按下非数值(运算符之一),数组 tab1 就会在运算符之前被推送到数组选项卡中。最后,当他按下计算()=屏幕显示带有tab.join('-')的选项卡。但它失败了。

<!DOCTYPE html> 
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>New Calculator</title>
  <link rel="stylesheet" href="calc.css">
</head>

<body>
  <p id="ecran"></p>
  <div id="btn">
    <input type="button" id="c1" onclick="printValue(this)" value="1" class="pad" />
    <input type="button" id="c2" onclick="printValue(this)" value="2" class="pad" />
    <input type="button" id="c3" onclick="printValue(this)" value="3" class="pad" /><br>
    <input type="button" id="c4" onclick="printValue(this)" value="4" class="pad" />
    <input type="button" id="c5" onclick="printValue(this)" value="5" class="pad" />
    <input type="button" id="c6" onclick="printValue(this)" value="6" class="pad" /><br>
    <input type="button" id="c7" onclick="printValue(this)" value="7" class="pad" />
    <input type="button" id="c8" onclick="printValue(this)" value="8" class="pad" />
    <input type="button" id="c9" onclick="printValue(this)" value="9" class="pad" /><br>
    <input type="button" id="c10" onclick="printValue(this)" value="0" class="pad" />
    <input type="button" id="c11" onclick="printValue(this)" value="+" class="pad" />
    <input type="button" id="c12" onclick="printValue(this)" value="-" class="pad" /><br>
    <input type="button" id="c13" onclick="printValue(this)" value="/" class="pad" />
    <input type="button" id="c14" onclick="printValue(this)" value="x" class="pad" />
    <input type="button" id="c15" onclick="reset()" value="reset" class="pad" /><br>
    <input type="button" id="c16" onclick="effacer()" value="clear" class="pad" />
    <input type="button" id="c17" onclick="calculate()" value="=" class="pad" />
  </div>
</body>
<script>
  let ecran = document.getElementById("ecran");
  let tab = [];

  function printValue(val) {

    let valu = val.value;
    let tab1 = [];

    if (!isNaN(valu)) {
      tab1.push(valu)

    } else {

      tab.push(tab1)
      tab.push(valu)
      tab1 = []
    }

    ecran.textContent += valu;

  }

  function calculate(tab) {
    ecran.textContent = tab.join('p');

  }


  function effacer() {
    tab.pop()
    ecran.textContent = tab.join('');

  }

  function reset() {
    tab = [];
    ecran.textContent = '';
  }
</script>
<!-- if(tab.join('').match(/^\d+([^0-9]{1}\d+)+$/)) {
        f(elt == "+") {
            res += parseInt(matchedTab[1][1]) 
        }
        else if(elt == "-") {
            res -= parseInt(matchedTab[1][1]) 
        }
        else if(elt == "*") {
            res *= parseInt(matchedTab[1][1]) 
        }
        else if(elt == "/") {
            res /= parseInt(matchedTab[1][1]) 
        }
         -->


</html>

标签: javascriptarrays

解决方案


推荐阅读