在没有eval()的情况下,在javascript中从数组中添加/除/乘数字和运算符 [英] adding / dividing / multiplying numbers and operators from array in javascript without eval()

查看:102
本文介绍了在没有eval()的情况下,在javascript中从数组中添加/除/乘数字和运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个计算器.挑战在于不使用eval().我从所有看起来像这样的输入中组成了一个数组:

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)";

所以我的问题是,在不使用eval()的情况下正确计算此方程式结果的方法是什么?

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

推荐答案

使用对象将运算符字符串映射到实现该运算符的函数.

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.

这篇关于在没有eval()的情况下,在javascript中从数组中添加/除/乘数字和运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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