问题
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