adding / dividing / multiplying numbers and operators from array in javascript without eval()

坚强是说给别人听的谎言 提交于 2020-01-11 14:50:15

问题


I'm making a calculator. And the challenge is not to use eval(). I made an array from all the inputs that looks like this:

numbers = [1,1,'+',2,'*',3,'-','(',4,'*',5,'+',2,'/',5,')'];

Then i convert this array to a string, remove the , and i get a string like this:

numberString = "11+2*3-(4*5+2/5)";

So my question is, what is the way to correctly calculate the result of this equation without using eval()?


回答1:


Use an object to map operator strings to functions that implement the operator.

var operators = {
    '+': function(x, y) { return x + y; },
    '-': function(x, y) { return x - y; },
    '*': function(x, y) { return x * y; },
    '/': function(x, y) { return x / y; }
};

The ( function should push the state onto a stack, and ) should pop the stack.




回答2:


Use this,

function notEval(fn) {
  return new Function('return ' + fn)();
}
numbers = [1, 1, '+', 2, '*', 3, '-', '(', 4, '*' , 5, '+', 2,' /', 5, ')'];
console.log( numbers.join('') + ' = ' +  notEval(numbers.join('')) );

Courtesy.



来源:https://stackoverflow.com/questions/35195046/adding-dividing-multiplying-numbers-and-operators-from-array-in-javascript-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!