当有些是字符串而有些是数字时,如何对数组中的项目执行数学运算?

时间:2019-06-24 01:42:30

标签: javascript jquery arrays math calculator

我正在尝试使用jQuery和JavaScript创建一个计算器。我的方法涉及将每个条目(数字和运算符)添加到数组,然后对它们执行数学运算。计算器本身是不完整的,因为无法根据单击的按钮使数组中的项相加/相减/相乘/除。

我曾尝试创建2个单独的数组,以为运算符不应该是两个数组,但这不起作用,并且会在以后产生更多问题。

<!DOCTYPE html>
<html>
<head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container w-25 align-left">
        <form>
                <div class="form-group">
                  <input type="text" class="form-control align-left" id="box" value='' placeholder="" readonly>
                </div>
              </form>
                </div>
<div class='container w-25'>
<div class="container pb-2">
    <button type="button" id='seven' value='7' class="num-btn btn btn-dark">7</button>
    <button type="button" id='eight' value='8' class="num-btn btn btn-dark">8</button>
    <button type="button" id='nine' value='9' class="num-btn btn btn-dark">9</button>
    <button type="button" id='divide' value='/'class="op-btn btn btn-dark">/</button>
</div>
<div class="container pb-2">
        <button type="button" id='four' value='4' class="num-btn btn btn-dark">4</button>
        <button type="button" id='five' value='5' class="num-btn btn btn-dark">5</button>
        <button type="button" id='six' value='6' class="num-btn btn btn-dark">6</button>
        <button type="button" id='multiply' value='*' class="op-btn btn btn-dark">*</button>
    </div>
    <div class="container pb-2">
            <button type="button" id='one' value='1' class="num-btn btn btn-dark">1</button>
            <button type="button" id='two' value='2' class="num-btn btn btn-dark">2</button>
            <button type="button" id='three' value='3' class="num-btn btn btn-dark">3</button>
            <button type="button" id='minus' value='-' class="op-btn btn btn-dark">-</button>
        </div>
        <div class="container pb-2">
                <button type="button" id='zero' value='0' class="num-btn btn btn-dark">0</button>
                <button type="button" id='decimal' value='.' class="num-btn btn btn-dark">.</button>
                <button type="button" id='plus' value='+' class="op-btn btn btn-dark">+</button>
                <button type="button" id='equals' value='=' class="eq-btn btn btn-dark">=</button>
            </div>
        </div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src='scripts.js'></script>
</html>
$('document').ready(function () {
    var num1 = []; //creates array for first number set
    var result = '';


        $('.num-btn').click(function () {
            num1.push($(this).prop('value')); //add each number to array
            arr1 = num1.join(' '); //joins numbers without comma using ''
            $('#box').val(arr1);
            console.log(arr1);
            result = (arr1);
            console.log(result);
        });


    $('.op-btn').click(function () {
        var operator = $(this).attr('value');
        num1.push(operator);
        console.log(operator);
        $('#box').val(''); //clears input #box
        console.log($('#box').val())
    });
    });

2 个答案:

答案 0 :(得分:0)

您可以使用评估函数result = eval(arr1);

更多参考,请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

$('document').ready(function () {
    var num1 = []; //creates array for first number set
    var result = '';


        $('.num-btn').click(function () {
            num1.push($(this).prop('value')); //add each number to array
            arr1 = num1.join(' '); //joins numbers without comma using ''
            $('#box').val(arr1);
            console.log(arr1);
            result = eval(arr1);
            console.log(result);
        });


    $('.op-btn').click(function () {
        var operator = $(this).attr('value');
        num1.push(operator);
        console.log(operator);
        $('#box').val(''); //clears input #box
        console.log($('#box').val())
    });
    });
<!DOCTYPE html>
<html>
<head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container w-25 align-left">
        <form>
                <div class="form-group">
                  <input type="text" class="form-control align-left" id="box" value='' placeholder="" readonly>
                </div>
              </form>
                </div>
<div class='container w-25'>
<div class="container pb-2">
    <button type="button" id='seven' value='7' class="num-btn btn btn-dark">7</button>
    <button type="button" id='eight' value='8' class="num-btn btn btn-dark">8</button>
    <button type="button" id='nine' value='9' class="num-btn btn btn-dark">9</button>
    <button type="button" id='divide' value='/'class="op-btn btn btn-dark">/</button>
</div>
<div class="container pb-2">
        <button type="button" id='four' value='4' class="num-btn btn btn-dark">4</button>
        <button type="button" id='five' value='5' class="num-btn btn btn-dark">5</button>
        <button type="button" id='six' value='6' class="num-btn btn btn-dark">6</button>
        <button type="button" id='multiply' value='*' class="op-btn btn btn-dark">*</button>
    </div>
    <div class="container pb-2">
            <button type="button" id='one' value='1' class="num-btn btn btn-dark">1</button>
            <button type="button" id='two' value='2' class="num-btn btn btn-dark">2</button>
            <button type="button" id='three' value='3' class="num-btn btn btn-dark">3</button>
            <button type="button" id='minus' value='-' class="op-btn btn btn-dark">-</button>
        </div>
        <div class="container pb-2">
                <button type="button" id='zero' value='0' class="num-btn btn btn-dark">0</button>
                <button type="button" id='decimal' value='.' class="num-btn btn btn-dark">.</button>
                <button type="button" id='plus' value='+' class="op-btn btn btn-dark">+</button>
                <button type="button" id='equals' value='=' class="eq-btn btn btn-dark">=</button>
            </div>
        </div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src='scripts.js'></script>
</html>

答案 1 :(得分:0)

您要执行的操作实际上有点复杂,因为特定的字符串值(例如*)需要触发特定的操作(例如乘法)
一种解决此问题的方法是使用下面的operation函数。您将为用户选择的每个操作运行一次此函数。

evaluate函数假定您已经将数字收集到一个数组中,并且将运算符收集到了一个单独的数组中。(这种分隔有助于防止类型错误,并易于说明如何需要执行许多操作。)该函数将数学结果累积在resultSoFar变量中,并在没有操作要执行时将其打印出来。

let nums = [8, 5, 2];
let ops = ["*", "+"];
evaluate(nums, ops);

function operation(a, operator, b){ // eg: operation(8, "*", 5)
  switch (operator){
    case "+": return a + b;
    case "-": return a - b;
    case "*": return a * b;
    case "/": return a / b; // This will fail spectacularly if b is zero
    default:
      console.log("Unknown operator: " + operator);
      return NaN;
  }
}

function evaluate(numsArray, opsArray){  

  // Requires numsArray to have exactly one item more than opsArray
  if(opsArray.length + 1 != numsArray.length){
    console.log("Error: Array lengths mismatch");
    return; // Function will stop here if lengths aren't compatible
  }

 // Starts out with the first number
  let resultSoFar = numsArray[0];

  // We care about the index of each item, which is the second argument 
  //   to the anonymous function that we pass to `Array.forEach`.
  // The first argument is not important to us, as its name implies.
  opsArray.forEach(function(_, index){ 

    // Applies the operation to `resultSoFar` and the next number
    resultSoFar = operation(resultSoFar, opsArray[index], numsArray[index + 1]);

  // (In the example, there are two operations to perform:
  //   The first time through the loop, 8 * 5 = 40
  //   The second time through the loop, 40 + 2 = 42)
  });
  
  console.log(resultSoFar);
}

我留给您收集用户的值(并在每次输入后更新显示)。
您可能想使用parseInt函数将输入中的值转换为数值。

注意:通过使用evaluate函数可以更简洁地实现Array.reduce函数,但是此示例使用更详细的语法,以便对不熟悉该函数(非常有用)的任何人更易于阅读。