Eval替代品 [英] Eval alternative
问题描述
此代码用作计算器,但codeacademy的便笺簿告诉我,eval是邪恶的。是否有其他方法可以在不使用eval的情况下执行相同的操作?
This code works as a calculator, but the scratch pad at codeacademy tells me that eval is evil. Is there another way to do the same thing without using eval?
var calculate = prompt("Enter problem");
alert(eval(calculate));
推荐答案
eval
将字符串输入计算为JavaScript,巧合的是JavaScript支持计算并理解 1 + 1
,这使其适合作为计算器。
eval
evaluates the string input as JavaScript and coincidentally JavaScript supports calculations and understands 1+1
, which makes it suitable as a calculator.
如果您不想使用 eval
,这很好,您必须自己解析该字符串,最后自己进行计算(不是完全是你自己)。看看这个数学处理器,它可以满足您的需求。
If you don't want to use eval
, which is good, you have to parse that string yourself and, finally, do the computation yourself (not exactly yourself though). Have a look at this math processor, which does what you want.
基本上你做的是:
- 用char读取输入字符串char(有这种问题的话)仍然可能)
- 构建您想要执行的操作树
- 在字符串的末尾,您评估树并进行一些计算
例如,您有1 + 2/3
,这可以评估到以下数据结构:
For example you have "1+2/3"
, this could evaluate to the following data structure:
"+"
/ \
"1" "/"
/ \
"2" "3"
然后你可以遍历从上到下的结构并进行计算。
首先你有+
,左边有一个,右边有一些表情,
所以你必须首先评估该表达式。所以你去了/
节点,它有两个数字子节点。知道了,你现在可以计算 2/3
并用结果替换整个/
节点。现在你可以再次上升并计算 +
节点的结果: 1 + 0.66
。现在你用结果替换那个节点,你剩下的就是表达式的结果。
You could then traverse that structure from top to bottom and do the computations.
At first you've got the "+"
, which has a 1 on the left side and some expression on the right side,
so you have to evaluate that expression first. So you go to the "/"
node, which has two numeric children. Knowing that, you can now compute 2/3
and replace the whole "/"
node with the result of that. Now you can go up again and compute the result of the "+
" node: 1 + 0.66
. Now you replace that node with the result and all you've got left is the result of the expression.
一些关于代码如何看待的伪代码:
Some pseudo code on how this might look in your code:
calculation(operator, leftValue, rightValue):
switch operator {
case '+': return leftValue + rightValue
case '-': return 42
}
action(node):
node.value = calculation(node.operator, action(node.left) action(node.right))
您可能已经注意到,树是这样设计的它尊重运营商优先权的方式。 /
的级别低于 +
,这意味着它首先得到评估。
As you might have noticed, the tree is designed in such a way that it honors operator precedence. The /
has a lower level than the +
, which means it get's evaluated first.
但是你详细说明了这一点,基本上就是这样。
However you do this in detail, that's basically the way to go.
这篇关于Eval替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!