如何在没有eval的情况下在javascript中编写计算器 [英] How to code a calculator in javascript without eval

查看:109
本文介绍了如何在没有eval的情况下在javascript中编写计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我搜索了高低,我找不到答案。我已经尝试了大约三次,并通过基本上将输入作为字符串存储在数组中,解析数字,然后打开运算符,以便评估整数,得到一个基本的一个,但我有一个找出链接逻辑真的很难。有没有人有什么建议?甚至可能只是伪造的代码?我真的不想使用eval。非常感谢

So, I've searched high and low, and I can't find an answer to this. I've attempted it about three times and gotten a basic one cranked out by basically storing the input in an array as a string, parsing the numbers, then switching on the operator, in order to evaluate the integers, but I'm having a really hard time figuring out the chaining logic. Does anyone have any suggestions? Of maybe even just the psuedocode? I really don't want to use eval. Thanks a lot

推荐答案

对于一个只有5个运算符(^,*,/,+, - )且没有括号的简单计算器,你可以做这样的事情。首先,将字符串转换为数字和运算符数组很方便。然后,我们按照优先顺序遍历数组查找每个运算符,并将运算符应用于它之前和之后的数字。

For a simple calculator with only 5 operators (^, *, /, +, -) and no parentheses, you can do something like this. First, it is convenient to turn the string into an array of numbers and operators. Then, we go through the array looking for each operator in order of precedence, and applying the operator to the numbers preceding and following the it.

function parseCalculationString(s) {
    // --- Parse a calculation string into an array of numbers and operators
    var calculation = [],
        current = '';
    for (var i = 0, ch; ch = s.charAt(i); i++) {
        if ('^*/+-'.indexOf(ch) > -1) {
            if (current == '' && ch == '-') {
                current = '-';
            } else {
                calculation.push(parseFloat(current), ch);
                current = '';
            }
        } else {
            current += s.charAt(i);
        }
    }
    if (current != '') {
        calculation.push(parseFloat(current));
    }
    return calculation;
}

function calculate(calc) {
    // --- Perform a calculation expressed as an array of operators and numbers
    var ops = [{'^': (a, b) => Math.pow(a, b)},
               {'*': (a, b) => a * b, '/': (a, b) => a / b},
               {'+': (a, b) => a + b, '-': (a, b) => a - b}],
        newCalc = [],
        currentOp;
    for (var i = 0; i < ops.length; i++) {
        for (var j = 0; j < calc.length; j++) {
            if (ops[i][calc[j]]) {
                currentOp = ops[i][calc[j]];
            } else if (currentOp) {
                newCalc[newCalc.length - 1] = 
                    currentOp(newCalc[newCalc.length - 1], calc[j]);
                currentOp = null;
            } else {
                newCalc.push(calc[j]);
            }
            console.log(newCalc);
        }
        calc = newCalc;
        newCalc = [];
    }
    if (calc.length > 1) {
        console.log('Error: unable to resolve calculation');
        return calc;
    } else {
        return calc[0];
    }
}
var calculateButton = document.getElementById('calculate'),
    userInput = document.getElementById('userInput'),
    result = document.getElementById('result');
calculateButton.addEventListener('click', function() {
    result.innerHTML = "The answer is " + calculate(parseCalculationString(userInput.value));
});

<input type="text" id="userInput" />
<input type="button" value="Calculate" id="calculate" />
<div id="result"></div>

(< a href =http://jsfiddle.net/L9a83udz/37 =noreferrer> jsfiddle )。为了允许括号,您可以告诉计算函数在开始查找任何其他运算符之前检查括号,然后在每组括号内的表达式上递归调用自身。解析功能也可以改进,例如删除任何空格并处理错误。

(jsfiddle). To allow parentheses, you could tell the calculate function to check for parentheses before it starts looking for any of the other operators, then recursively call itself on the expression within each set of parentheses. The parsing function can also be improved e.g. removing any white space and dealing with errors.

这篇关于如何在没有eval的情况下在javascript中编写计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆