JavaScript中的计算器

时间:2013-08-09 06:39:25

标签: javascript calculator

我在JavaScript中找不到一个好的计算器。

我第一次在我的数据上使用eval函数来获取结果,但是出现了错误。

所以我找到了这段代码:

function calculate(input){

   var f = { add : '+'
       , sub : '-' 
       , div : '/'
       , mlt : '*'
       , mod : '%'
       , exp : '^' };

   // Create array for Order of Operation and precedence
   f.ooo = [[ [f.mlt] , [f.div] , [f.mod] , [f.exp] ],
        [ [f.add] , [f.sub] ]];

   input = input.replace(/[^0-9%^*\/()\-+.]/g,'');           // clean up unnecessary characters

   var output;
   for(var i=0, n=f.ooo.length; i<n; i++ ){

  // Regular Expression to look for operators between floating numbers or integers
  var re = new RegExp('(\\d+\\.?\\d*)([\\'+f.ooo[i].join('\\')+'])(\\d+\\.?\\d*)');
  re.lastIndex = 0;                                     // be cautious and reset re start pos

  // Loop while there is still calculation for level of precedence
  while( re.test(input) ){
     //document.write('<div>' + input + '</div>');
     output = calc_internal(RegExp.$1,RegExp.$2,RegExp.$3);
     if (isNaN(output) || !isFinite(output)) return output;   // exit early if not a number
     input  = input.replace(re,output);
  }
   }

   return output;

   function calc_internal(a,op,b){
  a=a*1; b=b*1;
  switch(op){
     case f.add: return a+b; break;
     case f.sub: return a-b; break;
     case f.div: return a/b; break;
     case f.mlt: return a*b; break;
     case f.mod: return a%b; break;
     case f.exp: return Math.pow(a,b); break;
     default: null;
  }
   }
}

http://jsfiddle.net/vol7ron/6cdfA/

但是使用括号有一些问题,例如:(10+1)*5 = 11

所以我试图在JavaScript中找到一个好的计算器来计算字符串表达式。

感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

您可以使用math.js库,它带有强大的表达式解析器:

http://mathjs.org

答案 1 :(得分:0)

我没有javascript代码,但是如何评估字符串中复杂表达式的一般解决方案是使用Shunting-yard algorithm将其转换为RPN,然后使用Reverse Polish notation algorithm来获取结果。

答案 2 :(得分:0)

这是我最近提出的一个解决方案,作为在Javascript中使用clusure的练习。

var PocketCalculator = function() {

var allowedOperators = ["+", "-", "*", "/", "="],
    operations = {
        "+": function(a, b) {
            return a + b;
        },
        "-": function(a, b) {
            return a - b;
        },
        "*": function(a, b) {
            return a * b;
        },
        "/": function(a, b) {
            return a / b;
        }
    },
    cache = 0,
    makeOperation = function(b, f) {
        return function() {
            return cache = f(cache, b);
        };
    },
    prevOperation = operations["+"],
    operation = makeOperation(0, prevOperation);
return {
    clear: function() {
        cache = 0;
        prevOperation = operations["+"]
        operation = makeOperation(0, prevOperation);
    },
    push: function(operator, b) {
        if (allowedOperators.indexOf(operator) < 0)
            return;
        if (operator !== "=") {
            prevOperation = operations[operator];
            operation = makeOperation(b, prevOperation);
        } else if (b !== undefined)
            operation = makeOperation(b, prevOperation);
        return operation();
    }
};
};

答案 3 :(得分:0)

<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>

    <style type="text/css">

    ::selection { background-color: #E13300; color: white; }
    ::-moz-selection { background-color: #E13300; color: white; }

    body {
        background-color: #fff;
        margin: 40px;
        font: 13px/20px normal Helvetica, Arial, sans-serif;
        color: #4F5155;
    }

    a {
        color: #003399;
        background-color: transparent;
        font-weight: normal;
    }

    h1 {
        color: #444;
        background-color: transparent;
        border-bottom: 1px solid #D0D0D0;
        font-size: 19px;
        font-weight: normal;
        margin: 0 0 14px 0;
        padding: 14px 15px 10px 15px;
    }

    code {
        font-family: Consolas, Monaco, Courier New, Courier, monospace;
        font-size: 12px;
        background-color: #f9f9f9;
        border: 1px solid #D0D0D0;
        color: #002166;
        display: block;
        margin: 14px 0 14px 0;
        padding: 12px 10px 12px 10px;
    }

    #body {
        margin: 0 15px 0 15px;
    }

    p.footer {
        text-align: right;
        font-size: 11px;
        border-top: 1px solid #D0D0D0;
        line-height: 32px;
        padding: 0 10px 0 10px;
        margin: 20px 0 0 0;
    }

    #container {
        margin: 10px;
        border: 1px solid #D0D0D0;
        box-shadow: 0 0 8px #D0D0D0;
    }
    </style>




</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    $(".num").click(function(){

        var oprator = $("#val2").val();     
        var one = $(this).val();

        if (oprator=='') {  
        var val1 = $("#val1").val();          
        $("#val1").val(val1+one);
     }else{
        var val1 = $("#val3").val();
        $("#val3").val(val1+one);
     }


    });

    $(".opt").click(function(){

        var plus = $(this).val();
        $("#val2").val(plus);

    });

    $("#equle").click(function(){

        var plus = $("#equle").val();
        var v1 = $("#val1").val();
        var v2 = $("#val2").val();
        var v3 = $("#val3").val();
        var v1int=parseInt(v1);

        var v3int=parseInt(v3);


        if (v2=="+") {
            var z = v1int+v3int;
        }else if(v2=="-"){
            var z = v1int-v3int;
        }
        else if(v2=="*"){
            var z = v1int*v3int;
        }
        else{
            var z = v1int/v3int;
            }

        $("#val4").val(z);

    });

});


</script
<body>

<div id="container">
    <h1>Welcome to CodeIgniter!</h1>

    <div id="body">
    <table>
    <tr cospan="5">
    <td colspan="2"><input type='text' name="val1" value="" id="val1"/></td>
    <td colspan="1"><input type='text' name="val2" value="" id="val2"/></td>
    <td colspan="1"><input type='text' name="val3" value="" id="val3"/></td>
    <td colspan="1"><input type='text' name="val4" value="" id="val4"/></td></tr>
    <tr>

        <td><button type="button" class="num" id="one" value="1">1</button></td>
        <td><button type="button" class="num" id="two" value="2">2</button></td>
        <td><button type="button" class="num" id="three" value="3">3</button></td>
        <td><button type="button" class="num" id="four" value="4">4</button</td>
        <td><button type="button" class="num" id="five" value="5">5</button></td>
   </tr>
   <tr>     
        <td><button type="button" class="num" id="six" value="6">6</button></td>
        <td><button type="button" class="num" id="seven" value="7">7</button></td>
        <td><button type="button" class="num" id="eight" value="8">8</button></td>
        <td><button type="button" class="num" id="nine" value="9">9</button></td>
        <td><button type="button" class="num" id="ten" value="10">0</button></td>
     </tr>  
      <tr>  
        <td><button type="button" id="plus" class="opt" value="+">+</button></td>
        <td><button type="button" id="minus" class="opt" value="-">-</button></td>
        <td><button type="button" id="mul" class="opt" value="*">*</button></td>
        <td><button type="button" id="dev" class="opt" value="/">/</button></td>
        <td><button type="button" id="equle"  value="=">=</button></td>
         </tr>
    </table>    
    </div>


</div>

</body>
</html>